答:
You might want to check on Likedin groups related to programming language, such as ruby on rails, python, or any other popular open source language. I've already got the chance to see people inviting others to participate on their new open source projects, and what was good about it was that the person looking for new members actually expected inexperienced ones that would learn using his project.

Another option is google groups, yahoo groups related to a particular language. Depending on where you are located you might find up they are meeting to practice coding (specially coding dojo practitioners) and they might have people starting on open source projects as well.

Ohloh can provide you a quick view on projects that are being tracked, the amount of users and how long the project was up based on the code repository. While I find unlike that you will find an open source project being tracked as soon as it is started, you may find it useful to know of smaller open source communities.

Finally, looking for projects that have been recently forked may also help as well. Nightgale was forked from Songbird, a popular open source player that ended support for linux community users. They just released their full release. Something similar happened to foswiki few years ago, so this is a topic that might help you find starting projects that are promising.

Title: How to find just starting OpenSource project and Join or find programmers for own?

Body:
Is there any place on the web where can I join a team when they are just starting their project?

Is there any place where developers can make groups for projects?

I know there are some /dev/forums where you can have luck to find something interesting in some topic ... but the chances there are really low.

I know that you can find some projects on CodePlex or GitHub but they will be already started projects and it's not so easy to understand and join it ...

I want to find some place where new ideas comes to new teams.

So ... maybe starting project must already have a good base, but not to big base and then project leader must Promote it and find developers who like the idea ?

Sometimes that is really hard to catch such promotions.


问:
How can I advocate a semi-strict release schedule in a risk-averse environment?
Recently I've been increasingly plagued by what I would have to describe as one of my most frustrating and morale-killing experiences in this profession: Having to sit on a release that has been tested, re-tested, staged, and for all intents and purposes is ready to ship/deploy.

As an all-around solutions guy and not just a hardcore coder, I do understand and have even advocated the need for proper change control. But lately, the tenuous balance between covering our bases and shipping on time has gone all lopsided, and I've had little to no success in restoring it to something sane.

I'm looking for compelling arguments to help convince risk-averse management that:

The dev team should (or must) be able to set its own release schedule - within reason of course (1-3 months should be conservative enough for all but the biggest Fortune 500 companies);

Software releases are important milestones and should not be treated cavalierly; in other words, unnecessary delays/stoppages are highly disruptive and should be considered only as a last resort to some critical business issue; and

External (non-dev/non-IT) entities who want (or demand) to be involved as stakeholders have a responsibility to cooperate with the dev team in order to meet the release schedule, especially in the last week or so before the planned ship date (i.e. user testing/staging).

The above are assertions that ring true for me based on experience, but it looks like I'm now in the position of having to prove it - so I'm asking for something a little meatier here, if such a thing exists.

Can anyone who has had to "sell" the idea of a fixed (or maybe semi-flexible) release cycle to management give some pointers on what arguments/strategies are effective or persuasive and what is not? Aside from the obvious schedule contention and sunk costs, is there any hard data/evidence that would be useful in making the case that shipping is actually important, even in a "corporate" setting?

Alternatively, I'm open to hearing constructive arguments about why schedule flexibility (even over a period of weeks/months) is more important than shipping on schedule; it's hard for me to believe right now but maybe they know something I don't.

Note we have staged releases, and this went through every stage except production. Issues are tracked using a commercial bug tracker and every issue - 100% of them - that was assigned to this release was closed out. I realize it's difficult to believe and that's really precisely the point - it makes no sense that a 100%, feature-complete, fully-tested, approved-by-stakeholders release would be delayed by management for unexplained reasons, but that's what happened, that's what's been happening, that's the problem to be solved.

答:
You have clearly described the problems you are facing, however what I am unclear on why the managers are behaving this way. Can you clarify? For instance, you believe it's ready to deploy, does someone disagree, if so who and why? Are they ex governement beaurocrats

This sounds a lot like a capability vs desire alignment problem, you have the desire to release, but not the capablity (authority), those with the authority do not have the desire.

You need to find out why they lack the desire - it is marketing reason (keep it for another year while we milk the old version for a bit more), is it fear/confidence (If it has bugs, it will make us look bad, cost us money ...., lack of resource (Can't afford the cost of shipping/packaging/PR stuff), is it commercial where your some obscure sink to poor excess profits and they don't want you making money (Not as silly as it sounds).

I also suspect theres litle respect between parties involved, therefore reasonable adult discussions are not occuring.

Sorry - not the specific answer you have asked for, hopefully a couple of things to think about though.

ContentLicense: CC BY-SA 3.0


问:
What's the best practice for async APIs that return futures on Scala?
I have started a project to write an async PostgreSQL driver on Scala and to be async, I need to accept callbacks and use futures, but then accepting a callback and a future makes the code cumbersome because you always have to send a callback even if it is useless.

Here's a test:

```<code>"insert a row in the database" in {

  withHandler {
    (handler, future) =>
      future.get(5, TimeUnit.SECONDS)
      handler.sendQuery( this.create ){ query =>  }.get( 5, TimeUnit.SECONDS )
      handler.sendQuery( this.insert ){ query =>  }.get( 5, TimeUnit.SECONDS ).rowsAffected === 1
  }

}
</code>```

Sending the empty callback is horrible but I couldn't find a way to make it optional or anything like that, so right now I don't have a lot of ideas on how this external API should look like.

It could be something like:

```<code>handler.sendQuery( this.create ).addListener { query => println(query) }
</code>```

But then again, I'm not sure how people are organizing API's in this regard. Providing examples in other projects would also be great.

答: If you are talking async and futures in Scala, it is imperative that you read SIP-14: Futures and Promises. There were also some extensive discussions about it on the SIP mailing list, which is a google group, so you can find its archives.</p>


问:
hosting website from home
If I want to host a website from my home, I buy a domain name. Then, I get a static IP from my ISP. Next, I point it to the IP address of my home system. I can even use the SQL server installed in my system and not worry about the size. I am not talking about piles of servers here. Just one server.

I was wondering if it is that easy, why not do it? Is there something that I am missing here?  I am talking about moderately simple website. But does it matter?

答:
There are so many things that could go wrong:

Your computer might crash and your site will be down.

Your computer is less secure when it has a static IP.

You have to troubleshoot all of your server issues.

It is not very easy to update server-side software.

You might have to pay for a static IP (depending on your ISP).

Theft, fire, computer dies, internet screws up, and so on...

Also, after you do install everything, you still have to have a fair knowledge of what to do with it. You also can't use a web builder. And you would have to pay for cPanel.

Honestly, I can't see why you would set up a server by yourself (unless you want to learn PHP or other special reasons).

Edit:

To respond to comments, the OP did not say he was learning, but that he was hosting a small website. I agree with the fact that it would be nice for learning (which is why I have one) but he isn't learning (as far as we know).

Title: hosting website from home


问:
What is a good alternative to the name variable for a language that only has immutable references or labels?
For example, in functional languages, variables are single assignment and their values are immutable once assigned. So they have two states unbound and bound, once bound they can't be changed.

Is there some mathematical term or other computer science term that is most appropriate for such as thing? Something that semantically doesn't imply variance or mutability.

If not there doesn't exist such as term and if you were designing a language that had such constructs, what other than the word variable would you use to for these?

I am not really looking to poll for ideas, I am trying to figure out if there is already an accepted industry ( any industry ) term for such a thing.

答: Name. The same thing may be reasonably called by multiple names (x = 4; y = 4); and a name, once defined, never changes its referent. x = 2; x = 3 makes just as little sense as saying that an octopus is not an octopus.


答:
This is a great idea. Not only will you learn a lot about multiple topics (system administration, security, HTTP, the value of logging, detecting loss of contact with outer world, etc etc etc etc), but you will be keeping The Internet more personal, more human, more of what drew us to it in the first place.

Did everyone want to "surf the web" in 1996 just to see slick corporate PR, or be manipulated by targeted ads? No just no, but HELL NO. We wanted to surf the web to see what other people did, to see strawberry poptart torches, dancing hamsters and phony toilet-cams. Do it as fast as you can: get your web server on the net.

It sounds like you want to run a Windows-based server.  I know nothing of Windows, I run my personal servers (http://stratigery.com) on Linux. Switch to linux and you can email me questions any time.

Title: hosting website from home

Body:
If I want to host a website from my home, I buy a domain name. Then, I get a static IP from my ISP. Next, I point it to the IP address of my home system. I can even use the SQL server installed in my system and not worry about the size. I am not talking about piles of servers here. Just one server.

I was wondering if it is that easy, why not do it? Is there something that I am missing here?  I am talking about moderately simple website. But does it matter?


答:
It depends. If it's a small personal website, why not. If it's an enterprise-scale website requiring 99,99% or more service availability, it's certainly a bad idea.

Firstly, think about the cost:

Windows Server and Microsoft SQL Server already have a substantial price per licence. Do you prefer to pay dozens of thousands of dollars right now to host your server, or it's better to pay a small fee of $20/month for a basic hosting plan?

A dedicated server, even a basic one, has some cost too.

Also think about the power consumption. Running a server 24/24, 7/7 will obviously have an effect on your bills.

Secondly, think about the reliability:

It's 3 AM. Wake up! There is a small DDOS attack on your server. Your server is out. What is your strategy to be back online before 4 AM?

Haven't you ever said "Oh no, not again! My ISP suck! The internet is down again this month!"? Now imagine you have your server up and running, but not serving anything, since it's not connected to the internet any longer, and you have no idea how long it will take to the ISP to restore your connection?

Good morning. Your hard drive failed. By the way, all data is lost. Have a good day.

Are you ready for this scenario? Do you have scheduled backups? RAID? More generally, how do you manage redundancy of every component in your system? You can purchase a professional rack server which does all that. It will cost you $3 000. Ready?

Thirdly, think about the scalability, performance, and thousands of other things which are too long to list here. For example, one basic thing: most ISPs have an upload connection much more limited than a download connection. Are you ready to pay ten times you pay currently to your ISP just to have the same speed both ways?

Again, there is nothing wrong in hosting your personal website on your own computer if you don't care about the money. But there is a huge gap between a home-made hosting to a professional hosting which ensures service availability, which deals with cooling of their servers, which has UPS and other means needed to maintain the servers up if something happens with the power grid, etc.

Title: hosting website from home


问:
Software development project inception phase
Currently our team develops Web Applications and now we are going to Windows Forms applications.

I have created the inception phase for our Windows Forms project structure.

eg:

```
ApplicationSolution

--> Security Project(Login Authentication)

         a. Users will be registered with different applications in our application database.
           eg: ProjectApplicationId|ProjectName        | UserId
               1                   |ProjectApplication1| user
               2                   |ProjectApplication2| user

         b. Execute Application (Start)
         c. On Security dialog, application automatically get the userid of the user and see all the application it is registered using System.Security.Principal.WindowsIdentity.GetCurrent()
           eg: Prototype
              Welcome User! Please Choose Appliations you are registered on below:
                                 ProjectApplication1 <--this will be a dropdown
                                 ProjectApplication2
              Password: [*********************]
              [Access Application Button]
         d. User selects the application with its password
         e. If the password is incorrect (application.exit()) else execute Selected Application
             eg: ProjectApplication1 is selected then execute ProjectApplication1

--> ProjectApplication1

--> ProjectApplication2

--> Many to come ++

        if ProjectApplications has been closed then restart security Application.
```

My questions on this use case:

Is my use case possible?

Can you give me any recommendations ?

Currently we use setup and deployment to create installer in each Windows Forms application.

答:
c) "On security dialog..."

Automatically pulling a user id from an identity provider is a very convenient attribute of a system from a user's perspective.  However, I am not sure I would specify the provider to this level of detail in the use-case, though.  In addition, I would also want to specify and provide a fall-back method of providing a user-name to the security dialog in the event that the specified [default] provider is situationally not appropriate or unavailable for the user.  More than likely, a manually typed entry-mode of the username.

Are the passwords for users unique to each project?   If they are unique for each user on each project, the flow you presented makes sense.  Otherwise, if each user has only one password, regardless of project, I would require the password before presenting or suggesting a choice of project.

e)  "If the password is incorrect..."

I try to favoring only checking for the positive in the default case.  Here, I only want to know whethere the password was validated for the particular username.  Besides a common case of the incorrect password, there are be numerous other cases that would need similar handling to the incorrect password.  So in short, I would restate the step as:

If Password is validated, execute/present...else notify with reason not validated (incorrect/mismatch, connection issue, maintenance locked, load/license locked, access revoked, etc) and [allow/deny] retry.


答:
Joel Spolsky says that a software development team is a scheme for converting capital (money) into working software.  Honestly, from your question, it sounds like your team is good at that: you're getting decent software for reasonable amounts of money invested.

Now, of course the next step is to put the software into service.  Until your company chooses to do that, there's no way for them to harvest a return on their capital investment.  Software sitting on the shelf ready to deploy is kind of like inventory in the stockroom: the costs are sunk, the company's capital money is already spent. There's also an opportunity cost: your group chose to do this project rather than something else.

What's more, the value of newly developed software sitting on the shelf is kind of like the value of a crate of cheese sitting in a restaurant's fridge: It slowly rots. Its value declines because your competitors catch up. It also declines because it gets harder and riskier to put new software into service as its developers move on to other things. After a couple of years on the shelf, it may actually be worthless. In that case, your company has chosen to discard the capital they invested in developing it. It's possible that the owners of the company -- the shareholders -- will be displeased about this.

There's one thing you, as a developer, must figure out. Is your software really, truly, ready to deploy at the end of the release cycle you're proposing? Is it ready to go, or is there a whole bunch more work to do and money to spend as your company puts it into production? Does your company own the servers and software licenses you need to roll out your software? Does your work product include a deployment plan? Have the end-users been trained? Has the production data been converted? If your new software involves a change to the way your company does business, is the company ready to make that change? Have you worked out a scheme for running things in parallel, to make sure the new stuff works as well as the old stuff?

All those rollout costs can easily dwarf the cost of just developing the software. A wise project management team does its best to plan, budget, and schedule all that stuff. Have you done that work? Have you made it clear to management? If not, it's possible they're wise to go slow on your rollouts.

It's possible that a modern agile software rollout schedule is out of sync with the pace of change the rest of your company expects. Your end-users -- your stakeholders -- simply may not be able to absorb change at the rate your team can produce it.

It's also possible your management team is dysfunctional. Has your team developed something the rest of the company doesn't want? Does your new stuff threaten the heck out of your sales or production team? If so, some executive may be torpedoing it by saying it's too risky to roll out. There's nothing you can do about that unless you're the CEO.

You asked for compelling arguments for timely software rollouts.  There's one really compelling argument: return on investment. The company chose to invest in this software, and now they're choosing to waste the investment as your software slowly rots on the shelf.

A secondary argument for timely rollouts is the morale of your team. Hurry-up-and-wait is not a good way to motivate creative developers to do good work. You may lose your team if they don't get the satisfaction of seeing their work go into service.

Title: How can I advocate a semi-strict release schedule in a risk-averse environment?

Body:
Recently I've been increasingly plagued by what I would have to describe as one of my most frustrating and morale-killing experiences in this profession: Having to sit on a release that has been tested, re-tested, staged, and for all intents and purposes is ready to ship/deploy.

As an all-around solutions guy and not just a hardcore coder, I do understand and have even advocated the need for proper change control. But lately, the tenuous balance between covering our bases and shipping on time has gone all lopsided, and I've had little to no success in restoring it to something sane.

I'm looking for compelling arguments to help convince risk-averse management that:

The dev team should (or must) be able to set its own release schedule - within reason of course (1-3 months should be conservative enough for all but the biggest Fortune 500 companies);

Software releases are important milestones and should not be treated cavalierly; in other words, unnecessary delays/stoppages are highly disruptive and should be considered only as a last resort to some critical business issue; and

External (non-dev/non-IT) entities who want (or demand) to be involved as stakeholders have a responsibility to cooperate with the dev team in order to meet the release schedule, especially in the last week or so before the planned ship date (i.e. user testing/staging).

The above are assertions that ring true for me based on experience, but it looks like I'm now in the position of having to prove it - so I'm asking for something a little meatier here, if such a thing exists.

Can anyone who has had to "sell" the idea of a fixed (or maybe semi-flexible) release cycle to management give some pointers on what arguments/strategies are effective or persuasive and what is not? Aside from the obvious schedule contention and sunk costs, is there any hard data/evidence that would be useful in making the case that shipping is actually important, even in a "corporate" setting?

Alternatively, I'm open to hearing constructive arguments about why schedule flexibility (even over a period of weeks/months) is more important than shipping on schedule; it's hard for me to believe right now but maybe they know something I don't.

Note we have staged releases, and this went through every stage except production. Issues are tracked using a commercial bug tracker and every issue - 100% of them - that was assigned to this release was closed out. I realize it's difficult to believe and that's really precisely the point - it makes no sense that a 100%, feature-complete, fully-tested, approved-by-stakeholders release would be delayed by management for unexplained reasons, but that's what happened, that's what's been happening, that's the problem to be solved.


答:
The Internet is an incredibly hostile place. Automated attacks are constantly scanning for vulnerable servers. I haven't been involved in this business for years, but I know that around 2005, at our local university, the average life span of a server connected to the internet with a stock, default, install of Linux or Windows was about five minutes before it was compromised.

If you are are going to be responsible for a server that is connected to the Internet you are going to have to get up to speed on security issues, and you will have to continue to follow security news to stay abreast of new threats. If you want to learn this stuff, that's great. There's no better way to learn it then managing your own server. It is a lot of work though, and only you can decide whether it makes more sense to focus on your core interests.

Title: hosting website from home


答:
This is not a good idea to run your server yourself, out of your home, using your regular, consumer-based Internet, if you're doing it for a business.

The most important point that @MainMa mentioned is that regular, consumer Internet has an imbalance in download speed and upload speed. With most ISP's, the upload rate is roughly half that of the download rate.

When surfing the web, the upload rate is used when you browse the Internet for handshakes and HTTP requests with the server. If your upload speed is significantly reduced, then any web pages you try to visit will hang and have trouble loading.

A mouse chewed through the phone lines out on the street once and electrocuted itself, and although my download speed was fine, my upload speed was reduced to about 150Mbps. My Internet connection was terrible, and I was just browsing the net! Imagine what it would be like if you had other people using your upload bandwidth...

Also, imagine what the user experience on the other side is like. Anyone who tries to load content from your home Internet will only see about half the rate of your download speed. This just doesn't scale, as home Internet wasn't designed to handle this load.

Most organizations that host their own applications have T1 lines or a business-equivalent Internet. In general, it's priced significantly higher than home Internet.

Thus, if you're doing this just to learn, and don't expect to have any traffic whatsoever, and the computer you're on is securely isolated from the rest of your network, then it could be a fun experiment.

But if you're planning on running a business off of this setup, prepare to lose. This is not a case where you want to attempt to be "off the grid".

Title: hosting website from home


问:
Is the Waterfall software development methodology still viable?
In my experience, it seems as though the Waterfall model has proven to be too inflexible and non-responsive to requirements changes to be considered a viable method in the modern world of software development. The growth and proven track record of more agile, iterative methods seems to indicate that there is no reason why anyone should be following a process of rigid blocks that assumes little to no changes from project inception to product delivery.

Is is the waterfall development methodology still viable for delivering software systems, with respect to time, cost, and quality?

答:
Yes it is very much alive, though today it's the more common "V model" that is used.

In either case, the problem that Agile has is that the solution almost never ends, the customer can continue to request changes and the development will continue to iteratively resolve them. For a project that is based on time and materials costing, this works very well. For a project that has a fixed cost, it doesn't.

For these fixed-cost projects, the customer almost always expects pre-defined milestones to demonstrate progress, however, these are more of the formal written variety rather than working code. For customers like this, the written specifications become the project, one where the software development is a secondary consideration (as they assume, if you have a well-defined project, the software should be easy to develop). These companies are also the ones that make heavy use of cheap, outsourced development resources.

So, if you have a fixed pot of money or time, do not expect the requirements to change or are not allowed to change any requirements, and are expected to supply a strong set of written documentation, then the waterfall models are the only ones that make sense.

Agile can be introduced in the middle of these projects to do the development, but you still have a ramp-up phase where the specifications are created from requirements, and a ramp down phase where the software is installed and tested in situ. Agile doesn't respond well to these cases.


答:
One good reason for not doing this I don't see mentioned yet: if your home gets it's internet via ADSL.  Don't forget that "A" stands for asymmetric.  You might be able to suck http from other folks' sites at a nice 4-8Mbit/s, but if you only have 256-512kbps upstream, your site will seem very slow if it has any non-trivial image content and/or there are more than a few simultaneous users.

Apart from that, I'd say it's entirely possible.  I knew someone who ran a successful online business for years with the only web server being a machine under the desk in their home office.

Title: hosting website from home


答:
There's no reason why not - you can happily rent a server or a VPS and have the exact same problem.

Only there is 1 reason why you'd go for the VPS or dedicated server instead of one at home: the internet connectivity is much better at the datacentre than it is with your home connection. Sure, it costs a bit more, but you won't have to have a server whirring away in your back bedroom eating up all your electricity. You will also have a lot more tools to manage the thing too (like backup space and auto-reinstall).

The rest of the problem is all a learning exercise. I'd recommend Linux for your server as it runs the majority of the web, and there is much more information out there about managing, securing and maintaining it than there is with Windows.

Title: hosting website from home


问:
WCF/SOA - Why should I create parameter objects for simple requests
Our company is starting a fairly large SOA initiative.  We're doing a lot of stuff right: there's good communication; money for tools where appropriate; and we have brought on some good expertise to help us with the transition.

We're trying to develop standards that we can follow as a group, and one of the proposed standards is bothering me quite a bit:

We have standardized on the pattern where every operation takes a request object and returns a response object.

I realize that this is more or less a standard approach for a lot of folks, but I am asking why should I bother? (I'm not so good with received wisdom, I need some why).

Most of the services that I will be providing are simple organizational metadata retrieval.  For example, find the security policy for a particular user.  This needs a user id and nothing else.  The standard tells me that I should wrap this request in an object and wrap the returned policy in a response object.

My unease is amplified by a look at the WSDL that is generated from our contracts.  WCF generates request and response messages automatically and wraps even the request/response object.

I fully understand that if you're making a complex request then a complex input object is warranted.  That's what you would do even if services wren't involved.

My question is why should I automatically wrap requests and responses when:

It makes simple services less expressive

You would do it anyway for a complex service

WCF creates a request/response message anyway

I have found the following arguments in favor of this approach:

It supports versioning by allowing optional parameters to be slipped into the request object.

Back in the day, I did a fair bit of COM, and I would consider this almost an anti-pattern for versioning.  For some things, I suppose it would help, but I expect that where it would help, you already have a parameter object anyway.

It allows common data and behavior to be isolated to a base class

This one carries some weight with me.

It steers people away from an RPC style behavior and towards a messaging behavior

I've read this on Microsoft's site and heard it from our guru, but I still don't have a clear idea what they mean or why it's valuable.  Is it that natural looking interfaces make people tend to forget that they are calling a remote service?

I am looking at refactoring the signatures of perhaps 300 methods, so this is a non-trivial amount of pain.  I'm a huge fan of consistency in implementations, so I'm willing to take on the pain, it will just help to know that it will all be worth it in the end.

答:
Martin Fowler's notes on the Data Transfer Object are appropriate here, I think.

When you're working with a remote interface, such as Remote Facade (388), each call to it is expensive. As a result you need to reduce the number of calls, and that means that you need to transfer more data with each call. One way to do this is to use lots of parameters. However, this is often awkward to program - indeed, it's often impossible with languages such as Java that return only a single value.

The solution is to create a Data Transfer Object that can hold all the data for the call. It needs to be serializable to go across the connection. Usually an assembler is used on the server side to transfer data between the DTO and any domain objects.

The same might apply to requests.  As for RPC, and why its bad:

Is it that natural looking interfaces make people tend to forget that
they are calling a remote service?

I think that's true, but not the main reason. Another reason to avoid RPC is that it can encourage tightly coupled clients and services.


问:
For what types of applications is Python a bad choice?
I just started learning Python, and I'd like to get some more context on the language.

I realize that, in many cases, Python is a slow language relative to C or C++.  Thus, Python is probably not the best choice for applications that need to run as quickly as possible.

Outside of this, it seems like Python is a great general purpose language that is easy to read and write.  The available libraries give it a huge amount of functionality.  Outside of performance critical applications, where is it a bad choice to use Python (and why)?

答:
This really depends on what you mean by "bad choice".

If you mean applications where using Python is very difficult, then there are relatively few: the main one that comes to mind and hasn't been mentioned yet is code requiring high levels of correctness where languages with sophisticated types systems (Haskell, dependently typed languages) are better options.

If you mean applications where Python is sub-optimal (that is, there are better choices) then there are more but they are also more subjective. For example, in my admittedly limited experience, working on compilers and interpreters is much easier with algebraic data types, pattern-matching and more functional features than Python has. However, exhaustively listing applications like this is impossible as they vary per person.


问:
The false element in a Logical operation
I wish to know if there's some way to know which is the elemnet of a logic operation is false?

Example.

```<code>if( String.IsNullOrEmpty(obj1) || (String.IsNullOrEmpty(obj2) )
   throw("...............");
</code>```

How can I kown which one of those is the empty one?

答:
You cannot know which one of the subexpressions is empty, unless you repeat the checks.

Alternatively, you can separate the above code into two separate if statements, duplicating the throw("...") part.


问:
Are there established practices on versioning of a shared web service?
We are working on an ASP.NET-based XML Web Service that we will be using for our own purposes as well as using it as part of a product offering for our integration partners.

Once it goes live we will be working on future phases of the project, and it occurs to me that the service's details may need to change over time (method signatures, object types, etc.) and since we are not the only ones using the web service, we will need to have some level of coordination with our partners.

What I'm not sure about is the best way to do this. When we update the web service in such a way that the WSDL would be changed, should we deploy it to a separate URL? Should we overload the existing methods? Have differently named methods? Ideally we would just have everything coordinated and cut over to the new methods but I don't see that happening.

Are there established good ways to handle this?

答:
```<code>When we update the web service in such a way that the WSDL would be changed, should we deploy it to a separate URL?
</code>```

You could version the url (ie www.foobar.com/v2/service.svc) It would lead to a lot of sites though. What happens when you fix bugs? Would you still continue to support buggy versions? This is possible but not what I would advise.

```<code>Should we overload the existing methods? Have differently named methods?
</code>```

No. In a few versions time you may end up with loads of redundant methods and your code will be a nightmare to maintain.

```<code>Are there established good ways to handle this?
</code>```

I would recommend just having scheduled releases at set intervals (every quarter? ). That way your customers will have notice of the change, update their WSDL and run a few tests to check everything is still working. Its a matter of a few minutes every quarter so shouldn't be disruptive. The only changes that should break things is changing the signature of your contracts or methods. Adding new ones shouldn't disrupt old functionality or even need a wsdl update.

One other thing that may be worth looking into is using the IExtensibleDataObject interface to allow versioning in your datacontract (msdn here). Have a read through and see if its apropriate in your case.

Body:
When we update the web service in such a way that the WSDL would be changed, should we deploy it to a separate URL?

You could version the url (ie www.foobar.com/v2/service.svc) It would lead to a lot of sites though. What happens when you fix bugs? Would you still continue to support buggy versions? This is possible but not what I would advise.

Should we overload the existing methods? Have differently named methods?

No. In a few versions time you may end up with loads of redundant methods and your code will be a nightmare to maintain.

Are there established good ways to handle this?

I would recommend just having scheduled releases at set intervals (every quarter? ). That way your customers will have notice of the change, update their WSDL and run a few tests to check everything is still working. Its a matter of a few minutes every quarter so shouldn't be disruptive. The only changes that should break things is changing the signature of your contracts or methods. Adding new ones shouldn't disrupt old functionality or even need a wsdl update.

One other thing that may be worth looking into is using the IExtensibleDataObject interface to allow versioning in your datacontract (msdn here). Have a read through and see if its apropriate in your case.


答:
You can't know that in your code. But you can simply create two variables, that contain the parts of the condition and then check which one of them is true (at least one of them will) and which false (at most one of them).

```<code>bool isObj1Empty = String.IsNullOrEmpty(obj1);
bool isObj2Empty = String.IsNullOrEmpty(obj2);
if (isObj1Empty || isObj2Empty)
   throw("...............");
</code>```

Title: The false element in a Logical operation

Body:
I wish to know if there's some way to know which is the elemnet of a logic operation is false?

Example.

```<code>if( String.IsNullOrEmpty(obj1) || (String.IsNullOrEmpty(obj2) )
   throw("...............");
</code>```

How can I kown which one of those is the empty one?

Body:
You can't know that in your code. But you can simply create two variables, that contain the parts of the condition and then check which one of them is true (at least one of them will) and which false (at most one of them).

bool isObj1Empty = String.IsNullOrEmpty(obj1);
bool isObj2Empty = String.IsNullOrEmpty(obj2);
if (isObj1Empty || isObj2Empty)
   throw("...............");


问:
What quality level in the commit history can/should I expect/enforce?
I worked as a lone developer for a long time. During this time, I developed a way of formulating and ordering commit messages: Refactor first, describe exactly the reason for the commit in the message, link to the issue tracker, ... There is even a script to create several sorts of change log (public, company-internal, developer) from the commit history.
This way I always know, when and why the code in the codebase changed to the state it is now.

With the advent of interactive rebase and commit reordering, I can easily make sure that history (and, thus, documentation) looks exactly the way I want it to be. Bad code doesn't even get into the history. So, every commit has its well-defined purpose.

It took me years to evolve this practice, which I consider a good one. (Is it?) However, applying this to someone else's code changes (i.e., rewriting the history of someone else's changes) is, for me, a painfully time-consuming task. I have tried this in order to identify unnecessary or even faulty changes. The total size of the patch in question is slightly too big to be reviewed as a single unit, and there are a few questionable code changes.

In fact, it turns out that I cannot afford to control the code base as a "dictator". It just costs too much time. So I'd like to lose some control while maintaining a good quality of the code. Currently, I just don't see how to achieve this.

"How clean" should the history of a project be? Which format and granularity for the commits should I require? Should I ask the developer to reformat history (e.g., to split a commit), even if it would require education on how to split a commit after the fact? Should I teach developers to work on feature branches? Can commit templates help? How frequently should the changes by the others be reviewed?

答:
It depends how good the information in your issue tracker is.

If every single change is documented in the issue tracker, and linked to the issue, then it's not VITALLY important to have the change described in the commit history as well.  Of course, a one-liner always helps.  But so long as the anybody who's curious can find a description of the change, plus the reasons for the change, by following the link to the issue tracker, I think that's enough for most purposes.

Of course, if you occasionally have changes that don't get into the issue tracker; or if the information in the issue tracker is poor, then it's a whole lot more important to have a really detailed commit history.


问:
Pronunciation in programming?
How do you correctly or erroneously pronounce programming terms?  Any that you find need strict correction or history into the early CS culture?

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

regex = "rej ex" not "regg ex"?

sql = "s q l" not "sequel" (already answered, just i.e.)

Unixen

| = pipe not vertical bar?

bin = bin as in pin , not as in binary?

lib = lib as in library , not as in liberate?

etc = "ett see" , not "e t c" (as in /etc and not "&c")

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"

答:
We're a very international shop: there is no correct way, as long as we all understand each other.

Annoyance: # is hash in proper British English (and how we use it): £ or lb is pound to Europeans.

ContentLicense: CC BY-SA 2.5

Title: Pronunciation in programming?


问:
Check First vs Exception Handling?
I'm working through the book "Head First Python" (it's my language to learn this year) and I got to a section where they argue about two code techniques:

Checking First vs Exception handling.

Here is a sample of the Python code:

```<code># Checking First
for eachLine in open("../../data/sketch.txt"):
    if eachLine.find(":") != -1:
        (role, lineSpoken) = eachLine.split(":",1)
        print("role=%(role)s lineSpoken=%(lineSpoken)s" % locals())

# Exception handling
for eachLine in open("../../data/sketch.txt"):
    try:
        (role, lineSpoken) = eachLine.split(":",1)
        print("role=%(role)s lineSpoken=%(lineSpoken)s" % locals())
    except:
        pass
</code>```

The first example deals directly with a problem in the .split function.  The second one just lets the exception handler deal with it (and ignores the problem).

They argue in the book to use exception handling instead of checking first.  The argument is that the exception code will catch all errors, where checking first will only catch the things you think about (and you miss the corner cases).  I have been taught to check first, so my intial instinct was to do that, but their idea is interesting.  I had never thought of using the exception handling to deal with cases.

Which of the two is the generally considered the better practice?

答:
Basically Exception handling supposed to be more appropriate for OOP languages.

Second point is the performance, because you don't have to execute eachLine.find for every line.

ContentLicense: CC BY-SA 4.0

Title: Check First vs Exception Handling?


答:
In .NET, it is common practice to avoid the overuse of Exceptions. One argument is performance: in .NET, throwing an exception is computationally expensive.

Another reason to avoid their overuse is that it can be very difficult to read code that relies too much on them. Joel Spolsky's blog entry does a good job of describing the issue.

At the heart of the argument is the following quote:

The reasoning is that I consider exceptions to be no better than "goto's", considered harmful since the 1960s, in that they create an abrupt jump from one point of code to another. In fact they are significantly worse than goto's:

1. They are invisible in the source code. Looking at a block of code, including functions which may or may not throw exceptions, there is no way to see which exceptions might be thrown and from where. This means that even careful code inspection doesn't reveal potential bugs.

2. They create too many possible exit points for a function. To write correct code, you really have to think about every possible code path through your function. Every time you call a function that can raise an exception and don't catch it on the spot, you create opportunities for surprise bugs caused by functions that terminated abruptly, leaving data in an inconsistent state, or other code paths that you didn't think about.

Personally, I throw exceptions when my code can't do what it is contracted to do.  I tend to use try/catch when I'm about to deal with something outside of my process boundary, for instance a SOAP call, a database call, file IO, or a system call. Otherwise, I attempt to code defensively. It's not a hard and fast rule, but it is a general practice.

Scott Hanselman also writes about exceptions in .NET here. In this article he describes several rules of thumb regarding exceptions. My favourite?

You shouldn't throw exceptions for things that happen all the time. Then they'd be "ordinaries".

Title: Check First vs Exception Handling?

Body:
I'm working through the book "Head First Python" (it's my language to learn this year) and I got to a section where they argue about two code techniques:

Checking First vs Exception handling.

Here is a sample of the Python code:

```<code># Checking First
for eachLine in open("../../data/sketch.txt"):
    if eachLine.find(":") != -1:
        (role, lineSpoken) = eachLine.split(":",1)
        print("role=%(role)s lineSpoken=%(lineSpoken)s" % locals())

# Exception handling
for eachLine in open("../../data/sketch.txt"):
    try:
        (role, lineSpoken) = eachLine.split(":",1)
        print("role=%(role)s lineSpoken=%(lineSpoken)s" % locals())
    except:
        pass
</code>```

The first example deals directly with a problem in the .split function.  The second one just lets the exception handler deal with it (and ignores the problem).

They argue in the book to use exception handling instead of checking first.  The argument is that the exception code will catch all errors, where checking first will only catch the things you think about (and you miss the corner cases).  I have been taught to check first, so my intial instinct was to do that, but their idea is interesting.  I had never thought of using the exception handling to deal with cases.

Which of the two is the generally considered the better practice?


答: I think defensive programming hurts performance. You should also catch only the exceptions you are going to handle, let the runtime deal with the exception you don't know how to handle.</p>

Title: Check First vs Exception Handling?


答:
As you are no longer flying solo, you should ask your team first.

Theres no right answer to this question, it depends not only on your product, but on your team. Formulate a set of rules, best to enforce the important ones (e.g. Code commits must have a tracking number), and encourage a style for everything else.

You will need to learn to trust your team, and accept that dooing things different to how you want is not always wrong.

Title: What quality level in the commit history can/should I expect/enforce?

Body:
I worked as a lone developer for a long time. During this time, I developed a way of formulating and ordering commit messages: Refactor first, describe exactly the reason for the commit in the message, link to the issue tracker, ... There is even a script to create several sorts of change log (public, company-internal, developer) from the commit history.
This way I always know, when and why the code in the codebase changed to the state it is now.

With the advent of interactive rebase and commit reordering, I can easily make sure that history (and, thus, documentation) looks exactly the way I want it to be. Bad code doesn't even get into the history. So, every commit has its well-defined purpose.

It took me years to evolve this practice, which I consider a good one. (Is it?) However, applying this to someone else's code changes (i.e., rewriting the history of someone else's changes) is, for me, a painfully time-consuming task. I have tried this in order to identify unnecessary or even faulty changes. The total size of the patch in question is slightly too big to be reviewed as a single unit, and there are a few questionable code changes.

In fact, it turns out that I cannot afford to control the code base as a "dictator". It just costs too much time. So I'd like to lose some control while maintaining a good quality of the code. Currently, I just don't see how to achieve this.

"How clean" should the history of a project be? Which format and granularity for the commits should I require? Should I ask the developer to reformat history (e.g., to split a commit), even if it would require education on how to split a commit after the fact? Should I teach developers to work on feature branches? Can commit templates help? How frequently should the changes by the others be reviewed?


问:
Computers that operate exclusively on boolean algebra
I was wondering if there are any computers that operate exclusively on boolean operations. For example, no add, sub, mult, or div in the instruction set (although these could be emulated with the appropriate boolean code). Rather, the cpu would work by comparing 2 bits at a time, with instructions like and, or, xor. I realize that no modern computer would operate like this, but have any historical computers had an instruction set something like this?</p>

答:
Try labview's free download. It's pretty close to where you want to be, which is hardware. Circuit design has some tools that, like labview, abstract away some details in order to push up the bar on productivity, but underneath it all, it's all zeros and ones. Quarutus is another, similar option for building circuits that operate exclusively on boolean logic to accomplish some rather simple tasks. But it does help in understanding how computers in general operate.

All computers operate exlusively on boolean logic, this is just some lower-level options for building up your own ideas in a simple format. This does pay off if you're interested in, say, embedded systems.


答:
A Pragmatic Approach

You should be defensive but to a point. You should write exception handling but to a point. I'm going to use web programming as an example because this is where I live.

Assume all user input is bad and write defensively only to the point of data type verification, pattern checks, and malicious injection. Defensive programming should be things that can potentially happen very often that you cannot control.

Write exception handling for networked services that may fail at times and handle gracefully for user feedback. Exception programming should be used for networked things that may fail from time to time but are usually solid AND you need to keep your program working.

Don't bother to write defensively within your application after the input data has been validated. It's a waste of time and bloats your app. Let it blow up because it's either something very rare that isn't worth handling or it means you need to look at steps 1 and 2 more carefully.

Never write exception handling within your core code that is not dependent on a networked device. Doing so is bad programming and costly to performance. For example, writing a try-catch in the case of out of bounds array in a loop means you didn't program the loop correctly in the first place.

Let everything be handled by central error logging that catches exceptions in one place after following the above procedures. You cannot catch every edge case as that may be infinite, you only need to write code that handles expected operation. That's why you use central error handling as the last resort.

TDD is nice because in a way is try-catching for you without bloat, meaning giving you some assurance of normal operation.

Bonus point is to use a code coverage tool for example Istanbul is a good one for the node as this shows you where you aren't testing.

The caveat to all of this is developer-friendly exceptions. For example, a language would throw if you used the syntax wrong and explain why. So should your utility libraries that the bulk of your code depends on.

This is from experience working in large team scenarios.

An Analogy

Imagine if you wore a spacesuit inside the ISS ALL the time. It would be hard to go to the bathroom or eat, at all. It would be super bulky inside the space module to move around. It would suck. Writing a bunch of try-catches inside your code is kind of like that. You have to have some point where you say, hey I secured the ISS and my astronauts inside are OK so it's just not practical to wear a spacesuit for every scenario that could possibly happen.

Title: Check First vs Exception Handling?


答:
This almost belongs on CodeReview. Here is how I would deal with this fairly cleanly, without checking things twice:</p>

```<code>public void DoSomething(string obj1, string obj2)
{
    CheckStrArgNotEmpty(name: "obj1", value: obj1);
    CheckStrArgNotEmpty(name: "obj2", value: obj2);

    // Optionally:
    obj1 = obj1.Trim(); // obj1, obj2 are bad names btw
    obj2 = obj2.Trim();

    // The rest of the code ...
}

private static CheckStrArgNotEmpty(string argName, string value)
{
    if (!String.IsNullOrWhitespace(value)) // or IsNullOrEmpty ?
    {
        return;
    }

    string exceptionMessage = String.Format(
        "Argument named '{0}' is null or empty but it should not have been."
        argName);
    throw new ArgumentException(message: exceptionMessage);
}
</code>```

Body:
This almost belongs on CodeReview. Here is how I would deal with this fairly cleanly, without checking things twice:

public void DoSomething(string obj1, string obj2)
{
    CheckStrArgNotEmpty(name: "obj1", value: obj1);
    CheckStrArgNotEmpty(name: "obj2", value: obj2);

    // Optionally:
    obj1 = obj1.Trim(); // obj1, obj2 are bad names btw
    obj2 = obj2.Trim();

    // The rest of the code ...
}

private static CheckStrArgNotEmpty(string argName, string value)
{
    if (!String.IsNullOrWhitespace(value)) // or IsNullOrEmpty ?
    {
        return;
    }

    string exceptionMessage = String.Format(
        "Argument named '{0}' is null or empty but it should not have been."
        argName);
    throw new ArgumentException(message: exceptionMessage);
}


答:
Even nowadays you can find examples of such processors, for example in complex interlocking systems.

However, these processors are not off-the shelf, and typically the production numbers are so low that in the end these end up being implemented in programmable logic (such as FPGA).

Title: Computers that operate exclusively on boolean algebra

Body: I was wondering if there are any computers that operate exclusively on boolean operations. For example, no add, sub, mult, or div in the instruction set (although these could be emulated with the appropriate boolean code). Rather, the cpu would work by comparing 2 bits at a time, with instructions like and, or, xor. I realize that no modern computer would operate like this, but have any historical computers had an instruction set something like this?</p>


答:
In Python in particular, it is usually considered better practice to catch the exception. It tends to get called Easier to Ask for Forgiveness than Permission (EAFP), compared to Look Before You Leap (LBYL). There are cases where LBYL will give you subtle bugs in some cases.

However, do be careful of bare except: statements as well as overbroad except statements, since they can both also mask bugs - something like this would be better:

```<code>for eachLine in open("../../data/sketch.txt"):
    try:
        role, lineSpoken = eachLine.split(":",1)
    except ValueError:
        pass
    else:
        print("role=%(role)s lineSpoken=%(lineSpoken)s" % locals())
</code>```

Title: Check First vs Exception Handling?

Body:
In Python in particular, it is usually considered better practice to catch the exception. It tends to get called Easier to Ask for Forgiveness than Permission (EAFP), compared to Look Before You Leap (LBYL). There are cases where LBYL will give you subtle bugs in some cases.

However, do be careful of bare except: statements as well as overbroad except statements, since they can both also mask bugs - something like this would be better:

for eachLine in open("../../data/sketch.txt"):
    try:
        role, lineSpoken = eachLine.split(":",1)
    except ValueError:
        pass
    else:
        print("role=%(role)s lineSpoken=%(lineSpoken)s" % locals())


问:
Is switching from a CVCS to a DVCS a considerable bandwidth save?
So, I'm in a big geographically-distributed company, we use perforce and I'm starting to make the case for a DVCS with a whitepaper I was requested to write.

I was thinking that one of the arguments I could use is the bandwidth saved using a DVCS, and technically if there were binaries to download (there are, but they're not sync'ed every day) and enough developers downloading them one could see a substantial difference. Unfortunately that's an edge case and its all that I can think of (other than individual developers being able to work faster when diffing, committing locally, and all those other DVCS perks).

So, would there be an actual noticeable bandwidth save?, in what other cases?. Free cookie to anyone with actual empirical evidence (confirming or refuting).

Edit: It is just one of the arguments I'm trying to support and it's not at all the main one, I got at least 10 others... this is one of the "side-benefits" but I want to find out how real it is. Plus, I want to win over the IT guys =)

答:
I'm in the process of writing my own white paper about my experience with converting from SVN to Git as I've mentioned in the comments.

Here's how I won over our IT guys. I don't have the exact numbers off hand, but the VM containing the SVN repo for our project was near 12-14gb of usage. When it came to an actual checkout, it was near 4.06gb coming down. When I experienced this on my first day, I made it my #1 priority to move away from SVN as quickly as possible.

The first population of our repo resulted in a size of about 1.3gb - once I tweaked the .gitignore file, we dropped the repo size even more. I was bent on making the repo as lean as possible, so with some analysis, we ended up at 346mb.

I received a new workstation yesterday, and much like my first day, I had to clone the repository. Downloading the repo was extremely fast with compression on, and took about 9 minutes.

I hesitated in initially posting this as a response, as your mileage may vary significantly - my predecessors may have setup SVN poorly for all that I know. I think that you could (and should) setup a test environment and try the conversion to see what kind of metrics you'll realize and publish those into your paper.

On a more day to day basis, I have a ton of hooks setup to automate pulling between a few different servers, but definitely not enough remote activity to monitor bandwidth usage on a day to day basis. It is very hard to say without more detail whether or not you will realize a benefit there.


问:
Staying alert and awake while coding
What methods do you use to stay awake and alert while working?

Personally I drink coffee non stop throughout the day.  But I've also heard of this thing called exercise that should help too.  Does anyone else have tips and tricks to stay more awake and alert while working?  Redbull? Maybe a magic pill that won't require me to sleep?

答:
I'm like you - I drink a lot of coffee, and occasionally I feel my eyes begin to droop.  Then it's time to get up, walk around, drink some water (or some coffee).  Maybe even play a game of pool.  The main thing is to change something, and normally just getting away from the screen for 5 minutes is a big help.

If that doesn't work, it's on with the headphones.  Pick a choice of music that has a bit of pace (Black Stone Cherry, for example) and crank up the volume.  Just make sure they're decent headphones, as much to reduce the effect on coworkers as anything else.  These are good ones, especially for the money:  http://www.amazon.co.uk/gp/product/B000MRP1B4/ref=oss_product

Title: Staying alert and awake while coding


问:
Web development: no local server workflow
I'm considering the reengineering of my web development ecosystem. We use Git very successfully to deploy new changes to our Production, Staging, and Development servers. Traditionally, I've always had a copy of Apache on my local machine - in the interest of keeping my local machine as lean as possible, I'm considering running Apache in a non-local VM and syncing changes somehow.

My initial thought was to run something like rsync and cron (Mac development system) to monitor the directory for file changes and then sync them up. I have been tempted to use a separate branch in Git and writing a hook to have the Apache server pull in the changes, but versioning all of my changes may be unproductive, particularly on very experimental additions.

My question is, is there something I'm not considering in this workflow? This particular project requires ColdFusion, so am I going to realize significant benefits over not having Apache/CFIDE locally?

答:
It does not really matter if your server is local or on a separate machine; what matters is if you can test any changes to your code fast enough. For example, you should not have to wait not even a minute for a cron job to pull your code changes to the server. And typically you should test any changes to your code first, and then check them into you repository.

So for a separate machine, what you need is a quick possibility to transfer your code changes from your local machine to the dev server "on-demand". A simple shell script, logging on to the server, running some commands there, which you can run seamlessly from your local box should do this. How this script has to look like depends mostly on your network environment, perhaps you need only some ftpcommands, but since you mentioned rsync, I guess you have a shared file system available.

If this gets "fast enough" for you you will have to test by yourself in your environment. And perhaps you will have to do some optimizing (network speed, for example, may be a factor if you have a large code base with several ten thousands of files).


答: As a general rule, if you know a statement could generate an invalid result, test for that and deal with it. Use exceptions for things you do not expect; stuff that is "exceptional". It makes the code clearer in a contractual sense ("should not be null" as an example).</p>

Title: Check First vs Exception Handling?


答:
Böhm-Jacopini result states that every program can be implemented using sequence, repetition, and selection.

So using ONLY booleans makes no sense but if there are repetition control statements such as a FOR or WHILE loop and sequence any computable function can be expressed.


问:
Caching Business Objects in MVC application
I figured this was more of an architectural question, so I chose to post it here rather than Stack Overflow.

So I'm building an MVC web application and have just finished writing the code that wraps my calls into the DB (DAL) and gives me access via an interface to Create, Update, and Delete my Business Objects. Quick example just so you can get familiar before I go into my real question - here's how I would load up a stored record in the database for someone on the front end:

```<code>BusinessObjects.Record record = DAL.LoadRecord(int recordId);
</code>```

Now once the record is loaded up, I can provide it to the front end (web) via a Model to one of my pages, or by attaching it to the ViewBag or something similar. How it gets there isn't important or what I'm worried about, it's more so how I can maintain state in a stateless (web) environment.

The problem I am dealing with right now is, say I provide this record to the front end, and my page reads from it and generates a UI around it. At this point, the record is more or less gone. It has been created, passed, and read, but because of the stateless environment, is now lost. I can re-create this record based on the data I have on the front end on its way back, but is something like this usually handled by adding this record to the cache, and then just working with it there until it's fully ready to be persisted once again (something like Saver.SaveRecord(record);)?

This would make things a lot quicker for the user, because they wouldn't have to be calling Save and Load every single time a page switched or something happened, but I didn't know if this was the correct architecture or if there's a common pattern that I have ignorantly ignored. I've tried to load up some links and have just found examples of how to set something like this up, but what I really want to know is, should I be setting something like this up, or is there a better way to do it.

You'll have to excuse the beginner question. It's pretty obvious this problem has been solved many times, I'm just unaware of some of the more common patterns for doing so, and therefore wasn't sure exactly what to search for.

答:
The answer is "it depends". if you think about what is involved in both caching and getting the data from the database fresh, you instinctively assume it will be slower to get it from the db each time.

We tend to think this because the database is a persistent store, where stuff is written to the database. Therefore it must be slower than an in memory cache right?

Well not always. The db is designed to maximise throughput and also to reliably persist data. It has its own tricks regarding caching that may make it quicker to replay the same query over and over than to put the result in a cache and query that.

A separate cache may be quicker when the database is doing a lot of writes, or is located a way away from the web server, or any number of other options.

My suggestion would be to start with the simple solution that works (direct to db) and design your code in such a way that you can easily switch that layer for a caching layer should it become necessary later.


答:
It depends on whether your development stack involves a build step or not.

If it does, then adding a 'copy to development server' step should be added to your personal build configuration. If you rely on step debugging a lot, then check out whether your development environment supports remote debugging.

The other solution is to keep the source files on the remote server in the first place, and work on them there. Either ssh into the server and code over ssh (if you're a vi / emacs kind of guy, this works pretty well), or mount the relevant directories on the server locally.

Title: Web development: no local server workflow

Body:
I'm considering the reengineering of my web development ecosystem. We use Git very successfully to deploy new changes to our Production, Staging, and Development servers. Traditionally, I've always had a copy of Apache on my local machine - in the interest of keeping my local machine as lean as possible, I'm considering running Apache in a non-local VM and syncing changes somehow.

My initial thought was to run something like rsync and cron (Mac development system) to monitor the directory for file changes and then sync them up. I have been tempted to use a separate branch in Git and writing a hook to have the Apache server pull in the changes, but versioning all of my changes may be unproductive, particularly on very experimental additions.

My question is, is there something I'm not considering in this workflow? This particular project requires ColdFusion, so am I going to realize significant benefits over not having Apache/CFIDE locally?


答:
This is an interesting question. Before the analysis, I'll say that bandwidth savings shouldn't be the reason you switch to a DVCS. However, a related point is the load on the server and that will naturally go down with a DVCS: people are simply not using the server as often. When they use it, they use it for "simple" things like push/pull. Heavy-duty operations such as annotate and grep are done on the client.

We can investigate the bandwidth usage by looking at an example where a DVCS works particularly poorly: an example with an image file. The setup is like this:

You add a 10 MB image to your project. Since it's a compressed file format you cannot compress it further and the initial version takes up 10 MB in the repository.

You make 9 changes to the image. Delta compression is often useless for compressed formats so each new revision takes up an additional 10 MB in the repository.

The repository size is now 100 MB.

We can now compare the bandwidth used in with a centralized and a decentralized system. I'm a Mercurial developer so I'll use Mercurial as an example of a DVCS (but Git works the same). I'll use Subversion as the centralized version control system (CVCS):

Pushing new revision to server: hg commit; hg push vs svn commit.

The bandwidth is the same since you need to send a 10 MB delta to the server in both cases.

Pulling new revision from server: hg pull --update vs svn update.

A CVCS will let you download the 10 MB you need whereas a DVCS will ask you to download the intermediate revisions you're missing. So the bandwidth requirement depends on the update frequency:

If you do close collaboration and thus update often, then you end up with the same bandwidth requirement.

If you update less often, a DVCS will use more bandwidth.

Fresh checkout: hg clone vs svn checkout.t

Similar to the case above, but with very infrequent updates. So a DVCS will download more data than a centralized system.

Updating to old version: hg update vs svn update

A DVCS will require no bandwidth here, but a centralized tool will download 10 MB. Depending on your workflow, you might do this quite a lot when searching for bugs and so you can have significant savings here.

I think the requirements can be summarized as: you pay a larger up-front cost with a DVCS since you download everything. When that cost is paid, updates to old revisions are free. Updates to new revisions cost about the same as with a centralized tool, assuming you update frequently in both cases. Sending commits to the server is equal in the two systems.

This example shows that there is an overhead associated with a DVCS. However, in practice the overhead is manageable. For source code, the delta compression kicks in and does wonders to keep the size of your repository down.

An example from Mercurial:

Our biggest source file (mercurial/commands.py) is a 200 KB Python file. Since it's plain text, the initial version can be compressed to about 50 KB inside the repository.

We changed the file about 2200 times over the next five years. Delta compression means that each change takes up about 630 bytes in the repository.

The total size in the repository is 1.4 MB.

For for that file (probably our most used file) it makes a lot of sense to just download all 2200 revisions up-front — it's just another 1.4 MB to download! So the overhead is extremely low for text files and this is basically why DVCS can even be considered in the first place.

I've also looked at OpenOffice. The working copy for a checkout of tip is 2.0 GB. They have 276,000 changesets in their repository and the entire history takes up 2.3 GB. That is a 15% overhead thanks to excellent delta compression. The overhead for an initial checkout will be larger since a CVCS could compress the 2.0 GB down to maybe 500 MB. But they save bandwidth every time someone has to checkout an old revision to fix a bug — with a DVCS you already have the data right where you need it.

Finally, let me mention that Mercurial has a largefiles extension for handling files that take up too much space in the repository. It works by externalizing them so that they're only downloaded when needed. This effectively turns Mercurial into a CVCS with regard to those files.

Title: Is switching from a CVCS to a DVCS a considerable bandwidth save?

Body:
So, I'm in a big geographically-distributed company, we use perforce and I'm starting to make the case for a DVCS with a whitepaper I was requested to write.

I was thinking that one of the arguments I could use is the bandwidth saved using a DVCS, and technically if there were binaries to download (there are, but they're not sync'ed every day) and enough developers downloading them one could see a substantial difference. Unfortunately that's an edge case and its all that I can think of (other than individual developers being able to work faster when diffing, committing locally, and all those other DVCS perks).

So, would there be an actual noticeable bandwidth save?, in what other cases?. Free cookie to anyone with actual empirical evidence (confirming or refuting).

Edit: It is just one of the arguments I'm trying to support and it's not at all the main one, I got at least 10 others... this is one of the "side-benefits" but I want to find out how real it is. Plus, I want to win over the IT guys =)


答:
Have you tried simply exporting the version on the development server as a network share and developing that way?

I'm in the reverse situation. I have a workstation with limited storage, but plenty of grunt. I've got a NAS with a NFS export that I use as /home with little problems over gigabit ethernet. All the web files are on that share, along with most of the files the rest of the services on my PC use, and it's very responsive with a gigabit backbone. Keep in mind that in your case, all the services will be on the same local machine as the files, so it's only the editor that has to access the files across the network. You should see even better performance.


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
Management Disconnect

When those responsible for deadlines, features, staffing, etc get disconnected from the people responsible for delivering the project.  This can lead to:

Feature creep when the customer is talking with someone who doesn't understand feature cost

Man-month syndrome, where new developers are thrown into a project late enough to be more of a hinderance than a help

Unrealistic deadlines, created by people who have to deal with the business consequences of deadline decisions but not the implementation consequences.

Products that don't solve the problem, when customer-dev communication is hindered by management in the middle.

Poor risk management, where potential problems aren't communicated early enough between devs and management.

So, when it looks like management is uninterested in the project, is communicating poorly, isn't listening to the customers, or isn't listening to the dev team, run for the hills.


问:
How do you find time to work on Open Source Projects?
A bit of background: I've got a small open source project that I've started on, a basic framework which provides an object oriented means of generating HTML code (since I don't really like HTML, and I do like PHP). It has some released source, and a few downloads, but primarily, the project is for me, with the Open Source portion just being a side benefit.

The original project which caused me to be able to develop on this project has mostly gone into hibernation for the time being, which means that all the development I get to sink into it at this point is personal time only. Unfortunately, I'm currently working toward my bachelor's degree, studying for certifications, and I have a three month old baby at home. In short, by the time I get around to "me time", I rarely feel like doing work, but rather usually feel like just chilling out.

So, if there's anyone else out there who feels like they're in a similar position, what strategies have you used to keep yourself motivated toward working on the project? I would really like to at least be able to work on this until I have 100% spec coverage, but I haven't committed source in months. Anyone out there who can help?

答:
If you are asking yourself how to find time working on your open source project, this may indicates that you are willing to work on too much things at the same time.

You may not be able to physically handle everything and the consequence is that you will be bad in most things you will work on because of the lack of time and focus.

Think about your baby! And your bachelor degree! It's already 2 FULL TIME projects believe me!

Unless your open source project is more important than your baby or your bachelor degree, abandon your open source project for now.


问:
How I can hide dependencies from my Services?
Here's a service abstraction that I am working on :

```<code>public abstract class Service
{
public ILogger Logger{get;set;}

public IQueryManager QueryManager{get;set;}

public ICommandManager  CommandManager{get;set;}
}
</code>```

Then I have to call them in my class as usual :

```<code>Logger.Log("Something");

QueryManager.Query(new QueryObject()).Result;

etc.
</code>```

But I'd like to have some protected helper methods to make these sentences less verbose :

```<code>Log("Something");\\calls Logger.Log("Something")

Query(new QueryObject()); \\ returns QueryManager(new QueryObject()).Result
</code>```

Is there a way so that I can implement my dependencies so that they will be hidden from children of Service ? Is there an IoC container that allows me to use private properties to inject my dependencies ?

答:
You could have a constructor on your base class that takes the Logger and QueryManager as arguments. That way you can keep the fields private and still have them injected using constructor injection.

I.e. more or less like so:

```<code>public abstract class Service
{
    private ILogger logger;
    private IQueryManager queryManager;
    private ICommandManager commandManager;

    protected Service(ILogger logger, IQueryManager queryManager, ICommandManager commandManager)
    {
        this.logger = logger;
        // and so on..
    }
}

public class MyService : Service
{
    public Service(ILogger logger, IQueryManager queryManager, ICommandManager commandManager)
        : base(logger, queryManager, commandManager)
   {
       ...
   }
}
</code>```

Your container should then be able to resolve MyService, and inject the dependencies into the constructor.

Body:
You could have a constructor on your base class that takes the Logger and QueryManager as arguments. That way you can keep the fields private and still have them injected using constructor injection.

I.e. more or less like so:

public abstract class Service
{
    private ILogger logger;
    private IQueryManager queryManager;
    private ICommandManager commandManager;

    protected Service(ILogger logger, IQueryManager queryManager, ICommandManager commandManager)
    {
        this.logger = logger;
        // and so on..
    }
}

public class MyService : Service
{
    public Service(ILogger logger, IQueryManager queryManager, ICommandManager commandManager)
        : base(logger, queryManager, commandManager)
   {
       ...
   }
}

Your container should then be able to resolve MyService, and inject the dependencies into the constructor.


问:
Ternary operator (condition ? foo : bar) and the XOR (^) operator
I have read in a recent code review that both ternary operator (condition ? foo : bar) and the XOR operator ^ are rarely used in Java. Is it true?

If yes, is this because they are less readable? or some other reason.

答:
This is more of an opinion-based answer but in my case:

Indeed, for some reason I find the ternary operator less readable than an if-else construct.

As for XOR, probably most Java programs have no use for such low-level bitwise manipulations. For the most part, it seems to be just a relic inherited from C.

OwnerDisplayName: Kuldeep Jain

OwnerDisplayName: Tudor


答:
The ternary operator is well used, especially for short null-checks / defaults:

```<code>System.out.println("foo is "+(foo==null) ? "not set" : foo);
</code>```

Some people consider this not as readable as an if/else, but that was not the question.

The XOR bitwise operator is only used in bit-processing. If you need a bitwise XOR, then there is no way around it.

The XOR logical operator is indeed so rare, that I did not see it in the last ten year in Java in valid cases. This is also due to the fact, that the boolean XOR "does not scale" like || or &&. What I mean:

```<code>if( a && b && c && d ) ....   // it's clear what the intention is
if( a || b || c || d ) ....   // here also
if( a ^  b ^  c ^  d ) ....   // ???
</code>```

In the last case I would guess, the coder meant "only one should be true". But XOR is a beast. The coder got the beast and not what (s)he wanted.

That would be an interesting interview question: What is the result of the last if?

Title: Ternary operator (condition ? foo : bar) and the XOR (^) operator

Body:
I have read in a recent code review that both ternary operator (condition ? foo : bar) and the XOR operator ^ are rarely used in Java. Is it true?

If yes, is this because they are less readable? or some other reason.

Body:
The ternary operator is well used, especially for short null-checks / defaults:

System.out.println("foo is "+(foo==null) ? "not set" : foo);

Some people consider this not as readable as an if/else, but that was not the question.

The XOR bitwise operator is only used in bit-processing. If you need a bitwise XOR, then there is no way around it.

The XOR logical operator is indeed so rare, that I did not see it in the last ten year in Java in valid cases. This is also due to the fact, that the boolean XOR "does not scale" like || or &&. What I mean:

if( a && b && c && d ) ....   // it's clear what the intention is
if( a || b || c || d ) ....   // here also
if( a ^  b ^  c ^  d ) ....   // ???

In the last case I would guess, the coder meant "only one should be true". But XOR is a beast. The coder got the beast and not what (s)he wanted.

That would be an interesting interview question: What is the result of the last if?


答:
Lets look at the solutions here:

Adding a deploy command on your build configuration

That's a big no-no for development purposes. This is only to be used for QA by a different team (QA team preferably, but another developer who is not too familiar with the project would help).

Syncing local files to a remote location where the web server is located

This could work, however the time consumed to actually sync the data (or the constant checks) would be a lot of unneeded delay/overhead when you want to test a quick fix for example.

Keeping your local apache but turning it on/off

This could help lean your system, but still the overhead each time would be greater than the gain in performance.

My suggestion:

You should setup a workstation to work directly on a shared folder. This means that you save changes directly to the webserver folder. The overhead is minimal, and mostly unnoticed as by the time you hit save then alt+tab to hit refresh, the file has been already passed to the webserver. You keep your computer with the minimum software required only to develop, kind of like a terminal.


答:
I used to find the ternary operator difficult to parse, but I've since found that there are some places where it is very useful. These don't tend to be application logic, but logging.

For example:

```<code>log.info( "Object foo is " + ( foo.isEnabled() ? "" : "not " ) + "enabled" );
</code>```

To me, that's a lot neater than either

```<code>if ( foo.isEnabled() )
    log.info( "Foo is enabled" );
else
    log.info( "Foo is not enabled" );
</code>```

Or

```<code>log.info( "Foo is enabled : " + foo.isEnabled() );
</code>```

In summary, it's a question of where it's being used and for that.

As for bit-wise, I still struggle with those but that's because I'm used to working at a high level of abstraction, as other commenters have suggested. If I do come across somewhere in code that someone's decided to use that to be "efficient", the time wasted while I figure it out negates benefits.

Body:
I used to find the ternary operator difficult to parse, but I've since found that there are some places where it is very useful. These don't tend to be application logic, but logging.

For example:

log.info( "Object foo is " + ( foo.isEnabled() ? "" : "not " ) + "enabled" );

To me, that's a lot neater than either

if ( foo.isEnabled() )
    log.info( "Foo is enabled" );
else
    log.info( "Foo is not enabled" );

Or

log.info( "Foo is enabled : " + foo.isEnabled() );

In summary, it's a question of where it's being used and for that.

As for bit-wise, I still struggle with those but that's because I'm used to working at a high level of abstraction, as other commenters have suggested. If I do come across somewhere in code that someone's decided to use that to be "efficient", the time wasted while I figure it out negates benefits.


问:
What are the most important OO skills to show off in the job hunt?
I am in the market for new employment, and found a position were they asked me to create a programming sample based off an assignment. I blew the sample trying to get it done quickly one night, and got declined - only to be given a second chance recently.

The concern was that I didn't really demonstrate object oriented knowledge. I've rethought my approach but I figure it's worth asking: if you were hiring someone for an OO position, what skills would you most want to see them demonstrate they had a firm grasp on?

I want to be sure that I'm missing anything important this time around.

答:
Let me add few of my favorite OOP questions.

Usually, I start with simple question, and move on from there depending on the ability of the candidate.

Like someone told, most important questions are HOW and WHY and I choose the below topics to ask these!

1.How to choose between Abstract Class and Interfaces

Start with the difference, then ask the Qs in a design situation which one will you use?. The objective is to check the knowledge about the proper usage about the both.

2.How to choose between inheritance and Composition?

Here the candidate should be able to distinguish the has-a, is-a relationships. And should be able to choose the proper one in the given situation.

3.Can you be the compiler and JRE

I have this simple  code snippet;

```<code>class A {

}

class B extends A {

}
</code>```

From the above I start with the below code,

```<code>A a = new B();
B b = new A();
</code>```

There are lots of questions here like which of them will compile? WHY? WHY NOT?
What we can do to make it compile what will happen at run-time.

Then in the same example, add methods in both classes and you can move on to the method overriding and overloading etc..

As I told in the beginning these are only titles, you can go deeper in all these topics.

Body:
Let me add few of my favorite OOP questions.

Usually, I start with simple question, and move on from there depending on the ability of the candidate.

Like someone told, most important questions are HOW and WHY and I choose the below topics to ask these!

1.How to choose between Abstract Class and Interfaces

Start with the difference, then ask the Qs in a design situation which one will you use?. The objective is to check the knowledge about the proper usage about the both.

2.How to choose between inheritance and Composition?

Here the candidate should be able to distinguish the has-a, is-a relationships. And should be able to choose the proper one in the given situation.

3.Can you be the compiler and JRE

I have this simple  code snippet;

class A {

}

class B extends A {

}

From the above I start with the below code,

A a = new B();
B b = new A();

There are lots of questions here like which of them will compile? WHY? WHY NOT?
What we can do to make it compile what will happen at run-time.

Then in the same example, add methods in both classes and you can move on to the method overriding and overloading etc..

As I told in the beginning these are only titles, you can go deeper in all these topics.


答:
Depending on the version of the framework, you can create extension methods on object.

```<code>public static void Log(this YourTypeNameHere current, string message)
{
    current.Logger.Log(message);
}
</code>```

Edit updated to reflect feedback below. Put your class name or a super type, or an interface it implements on which Logger exists where it says YourTypeNameHere.

Title: How I can hide dependencies from my Services?

Body:
Here's a service abstraction that I am working on :

```<code>public abstract class Service
{
public ILogger Logger{get;set;}

public IQueryManager QueryManager{get;set;}

public ICommandManager  CommandManager{get;set;}
}
</code>```

Then I have to call them in my class as usual :

```<code>Logger.Log("Something");

QueryManager.Query(new QueryObject()).Result;

etc.
</code>```

But I'd like to have some protected helper methods to make these sentences less verbose :

```<code>Log("Something");\\calls Logger.Log("Something")

Query(new QueryObject()); \\ returns QueryManager(new QueryObject()).Result
</code>```

Is there a way so that I can implement my dependencies so that they will be hidden from children of Service ? Is there an IoC container that allows me to use private properties to inject my dependencies ?

Body:
Depending on the version of the framework, you can create extension methods on object.

public static void Log(this YourTypeNameHere current, string message)
{
    current.Logger.Log(message);
}

Edit updated to reflect feedback below. Put your class name or a super type, or an interface it implements on which Logger exists where it says YourTypeNameHere.


问:
How close have we gotten to automating code writing?
And I don't mean Autocomplete or automatic code snippets as inserted by modern day editors, or polymorphic code. But what is the state-of-the-art in programs that can go through given inputs and types and information of the desired outputs and output a valid piece of code in a language of choice. I am aware of Genetic Programming, Gene Expression Programming but I don't know of any other efforts. Also googling doesn't turn up much.

Is anyone aware of any advancements on this front?

Edit: When i say "output a valid piece of code", I mean an AI or something similar working out the logic and the flow of control and implement it in an imperative language. Imperative language only, since that's the tough part. Nevertheless, if you know of any new languages being developed to support this kind of idea, please do mention, as maybe our current set of languages are not suitable for the kind of early AI we may first chance upon.

答:
With your question I believe you are asking how much future development will be able to minimize the amount of work a software developer will have to do. Even if you have an AI that can write your whole program, you still have to tell it what to do, just like for an automatic car builder, you still have to give it a blueprint, and that blueprint requires some work.

And if you have an AI, you still have to teach it and it will have to learn through several projects. Therefore, I don't think that an AI is suitable for this kind of work, but rather a more deterministic approach, using code generators. These code generators can become very complex, but need not necessarily employ machine learning.

That said, there already exists research in the areas called Feature-Oriented Software Design and Aspect-Oriented Software Design. These deal with assembling software applications by selecting some features which it should have, and then code is generated for that. The goal is to have implementations for several features that appear repeatedly in a particular domain and assemble them like building blocks, as suitable for your particular application. For web development for example, features would include transactions, statistics, scalability, logging and whatever you can think of as recurring characteristics of different web apps.

Features and aspects are different than components, as they are usually cross-cutting concerns. Take for example logging. You can't just take a library and include it in your application and say you've got logging now. You have to spread your logging calls all over your code, and that is where code generators are handy. I've recently heard about all this stuff from this two part interview on Software Engineering Radio.

It seems that this kind of research is quite trendy in Europe, and Germany in particular, even in the industry, as I can say from personal experience. Code generation can be useful for generating the necessary infrastructure code, so that the developer can focus exclusively on implementing the specific behaviour of his application and not bother with the same side-issues on every different project.

It remains to be seen how much that application-specific code can be narrowed down. It certainly can't be eliminated completely, only reduced to some sort of blueprint, as I mentioned in the beginning.


问:
How does image editing software change image contrast?
How does Photoshop or other image editing software change an images contrast? What does contrast mean when we process an image pixel by pixel? Or what does image contrast mean at all?

Here I created a very basic image to understand image contrast. This is a 10×10 pixels image that gets a 100% non-legacy contrast adjustment in Photoshop. The only change I saw was in gray colors that were lighter after applying the contrast.

Before and after contrast:

答: Contrast is fairly simple. Increasing contrast means making bright pixels brighter and dark pixels darker; decreasing contrast is the opposite. So what you do is, per pixel: calculate the pixel's brightness, and move it toward or away from a center value (0.5 if your brightness range is 0 to 1).</p>


答:
Use what ever works well in..

your chosen programming language in terms of code readability and efficiency

your team and the set of agreed code conventions

Both exception handling and defensive programming are different ways of expressing the same intent.

Title: Check First vs Exception Handling?


答:
Actually, there are two very different algorithms in Adobe Photoshop CS3 or later.

The old one just shifts linearly the color of a pixel. The second one works proportionally. If your intent is to understand, in general, how contrast is applied, use the legacy contrast only. Here's an image showing a difference:

When using legacy contrast, you see that it's much more intuitive from developers point of view. It actually lightens the dark pixels, and darkens the light ones when reducing the contrast. When increasing the contrast, you will see the same happening with gray color (turning lighter, then white at 100%), while blank and white staying the same.

From the point of view of photographers, on the other hand, this doesn't make any sense. As you can see below, when applied to real images, the new contrast algorithm has much better visual results than the old one:

See also:

Better Brightness And Contrast In Photoshop CS3: describes the difference between legacy and new contrast in Photoshop,

Brightness Calculation in Digital Image Processing (PDF) is explaining scientifically the brightness and contrast editing algorithms.

Title: How does image editing software change image contrast?

Body:
How does Photoshop or other image editing software change an images contrast? What does contrast mean when we process an image pixel by pixel? Or what does image contrast mean at all?

Here I created a very basic image to understand image contrast. This is a 10×10 pixels image that gets a 100% non-legacy contrast adjustment in Photoshop. The only change I saw was in gray colors that were lighter after applying the contrast.

Before and after contrast: