答:
I have used this technique exclusively for a web application we're working on. My backend is hosted on Google App Engine using the Java SDK, and my frontend uses HTML, CSS, and JavaScript (with jQuery).

The project is a smaller one with just myself and a Web designer, and we both feel that this method has helped us work a lot faster and get something to market much sooner.

Advantage: Working with Web Designers

The major advantage of this technique is that the Web designer, who knows some PHP but does not consider himself a programmer, can work unencumbered in the HTML and CSS without having to wade through countless lines of JSP, taglib tags, and other server-side markup that we've been told for years is supposed to make a front-end developer's life much easier.

Without all of the server-side markup, we've been more agile. The web designer has directly swapped out and revised his original design 3 or 4 times, with very few changes on my part.

His comment to me was that he felt like the HTML was alive in that he could edit it and then immediately see the changes on his machine with dynamic data. We've both benefit by this in that the integration is mostly automatic.

Server-side code and HTML/CSS Handoffs

In past projects, he's had to handoff the HTML and CSS to Java developers who would then take his HTML and CSS and completely rewrite it using JSP technology.  This would take lots of time, and would usually result in subtle yet important differences in the actual rendering of the pages as well as it's validation in the W3C validator.

Overall, we're both quite happy with this technique, and I still have zero JSP pages or server-side code in my HTML pages.

Pitfalls of the REST/JSON Technique

Perhaps the biggest pitfalls are ones that we haven't encountered yet. I fully expect to have some disagreements with more experienced Java developers who have been brainwashed by what the Apache foundation and the Spring team have told them regarding how tag libraries make it easier for frontend developers to work with the code. I fully expect there to be a learning curve as this project expands and we take on more developers who might have to unlearn these outdated techniques that, in my experience, have made the Web designers' job more difficult.

Another pitfall is that the JavaScript code has become very massive. This is more of a problem perhaps because I'm using this technique for the first time, and because we've introduced some slight technical debt in working towards a rapid release. Perhaps picking a better framework would have helped alleviate a lot of the bulk of the code. In my opinion, none of this has been a showstopper, and I'm encouraged to continue using this technique and refine my skills in this area.

Advantage: Other Applications Can Be Built On the Platform

Lastly, I should mention a hidden advantage. Because there is a nice degree of separation between my backend RESTful Web services and my frontend, I've also created a platform that I can easily extend.

One of our operations guys wanted to try a proof of concept in another application, and thanks to my RESTful services, we were able to create an entirely different frontend to the application to solve a completely different problem. The rapidly developed proof of concept used it's own HTML, CSS, and JavaScript, but it used the RESTful services as the backend and datasource.

In the end, another project manager saw what I had done, and it became immediately clear that the feature needed to be more than just a proof of concept, so his team implemented it.

I can't emphasize enough how reusable this architecture is, both at the application level as well as the HTML/CSS/JavaScript level, and I would definitely encourage you to try this in your next project.


问:
Estimating Cost of modifying someone elses code
I am relatively new to web development and haven't had to provide estimates for many large projects yet (my last large project was just paid for by the hour without a strict deadline or budget).

A client is asking me to provide a cost and time estimate for providing a myriad of changes to another developers code for a website (php/mysql backend).

Can anyone provide some advice or links on how to go about analyzing and estimating this? The code is horrible (the website was originally outsourced to india years and years ago) and it's hard to know if I'm going to suddenly hit hurdles and blow my estimates out of the water.

答:
You could quote a total based on the estimated hours of work, clarifying your assumptions and the fact that any additional time required will be added on.  This way if you go under (unlikely) you come out ahead.

Make sure the quality of existing code is clear to the client.  If they are reasonable they should be accommodating to the flexibility, otherwise be prepared to walk away.

I was in this situation when I started out and unfortunately Stack Exchange did not exist at that time. I quoted a fixed price and had to bail on the deal two months in.  I lost the money and burned a bridge since I could not deliver.

ContentLicense: CC BY-SA 3.0


问:
Is it safe to download VS11/.NET4.5 beta and still deploy to servers with .NET 4.0?
I've been wanting to try out VS2011 and .NET 4.5 beta, but the upgrade path is confusing at best. If I understand what I've read, the .NET 4.5 framework overwrites the .NET 4.0 libraries on your local machine, so libraries such as mscorlib.dll and System.dll will be replaced with the 4.5 version - fully backward compatible, but still different.

If I'm developing ASP.NET sites with VS2011, and assuming I don't use any of the new 4.5 features in the code, do you know of any issues I might have by deploying to a web server with only the .NET 4.0 framework? I wouldn't expect any problems since it's the same CLR, but I'd like to know for sure before I do it.

There's always the option of keeping a separate virtual dev machine for 2011/4.5 so that I can develop on 4.5, but go back to my original 4.0 machine to compile and publish, but I'd rather not go that route if I don't have to.

Thanks

答:
It's true, but not an issue. Looking in the frameworks directory where you have one directory per version, there isn't one for 4.5. However, I have VS2010 and VS11 on this machine and they coexist happily.

When you start VS11 you can pick 4.0 or 4.5 from the list of target frameworks. VS2010 of course still only targets 4.0. *(of course you can pick 3.5 and 2 too).

As for deployment it isn't an issue. I've deployed to machines with just 4.0 installed and it just works as you'd expect. I haven't deployed any 4.5 code yet though.


问:
How does one interface C++ with the web (at Google, for example)?
Google is well known for the ridiculous amount of C++ they've coded over the years. Correct me if I'm wrong, but a large part of Google's core search engine is written in C++, isn't it? How does one take a program written in C++ and interface it with a website?

Note: I'm not looking for how Google in particular does this, just how it might be done in general.

答:
Like any other language....

Open a TCP socket, send and receive http messages. Parse them and do stuff based on content.

Look at Qt for an example on a c++ framework that supports some basic http functionality.

There are also dedicated web frameworks for C++. Not many nor widely used, AFAIK. Probably because if you do web via C++, you are doing something very specialized anyway and want full control over everything.


答:
Client-server architecture lets this happen.

C++ may be used to develop the server.

On the client side, web technologies may be used to communicate with the server.

Title: How does one interface C++ with the web (at Google, for example)?

Body:
Google is well known for the ridiculous amount of C++ they've coded over the years. Correct me if I'm wrong, but a large part of Google's core search engine is written in C++, isn't it? How does one take a program written in C++ and interface it with a website?

Note: I'm not looking for how Google in particular does this, just how it might be done in general.


答:
Any web software will only send and receive messages through sockets, that's all. You could use any language to do this, it's not specific to languages.

However, you'd better not reinvent the wheel for this kind of work so most languages that are used to do web applications have their set of framework that does the basic communication for you, to allow you to concentrate on the specificities of your project. Ruby have ROR, Python have Django and others, Java as ...etc.

C++ historically didn't have any similar framework until recently:

a modern-C++ way of doing it is to use something like CPPCMS;

there is also an effort to setup a standard library for web dev. in C++, one of them being cpp-netlib;

Recently there have been a release of a cross-platform REST API library for C++11 from Microsoft called Casablanca which also helps;

Now, the "ridiculous amount of C++" that Google is built over is necessary because you need to have very-high-performance modules to solve the kind of problems Google solves. Good luck trying to do the same without any module written in a language focused on performance. I recommend reading the CPPCMS wiki about this subject to understand better. For historic facts, Amazon, Google, Facebook (see Hip Hop and recent Alexandrescu interviews) and some other really big web services do have cores in C++, for obvious computational reasons that are more important than the time lost on programmer productivity.

CPPCMS and cpp-netlib being open source, you can study them if you want to know how to make an application work as a web service using C++. That said, any application that can listen to ports and send data to port can potentially do this, it's all about protocoles (TCP/IP, HTTP, etc.), not code.


问:
Pros and cons of an HTML/JavaScript only web app
I come from an ASP.NET forms background and have found server side coding very powerful in the past. More recently, however, I have been wanting to phase out the server side code of the front-end and replace it with pure HTML/JavaScript, which accesses the data through JSON webservices. I have no real experience in this, and so I would like to hear whether this is a tried and tested model. Also, what are the pitfalls surrounding it?

I find ASP.NET user controls very useful, so I would like to keep the theory behind it by storing markup templates in separate HTML files on the server. These will be retrieved and used through jQuery AJAX and the jQuery HTML templates plugin respectively.

Any input will be extremely appreciated.

P.S. Sorry for the noob question, but is this type of Web architecture what is referred to as web-2.0 or am I completely off-track?

答:
If you're still using ASP.NET WebForms and want to speed up your applications, here's what you should do:

Design your application with SOLID in mind

Disable ViewState on all pages and user controls

Don't use server side controls

<%: VeiwModel.Title %> instead of < asp:Literal id="Title" runat="server">

In backend, override OnInit method and do all the initialization there:

protected override void OnInit(System.EventArgs e)
{
    CreateViewModel();
    base.OnInit(e);
}

Compress all .css and .js files into 1 using SquishIt

Lazy load images

Cache complex objects

Finally, check out www.porsche.se. Isn't that a damn fast website?


问:
What's so bad about the DOM?
I keep hearing people (Crockford in particular) saying the DOM is a terrible API, but not really justifying this statement. Apart from cross-browser inconsistencies, what are some reasons why the DOM is considered to be so bad?</p>

答:
Crockford has given an extensive presentation titled "An Inconvenient API: The Theory of the Dom" where he more or less explains his opinions on the DOM. It's longish (1h 18m), but as most Crockford's presentations it's quite enjoyable and educative.

Cross browsers inconsistencies seems to be his main concern, and I agree it's the single most annoying thing about the DOM. He identifies:

Proprietary traps (browser and server traps),

Rule breaking,

Corporate warfare,

Extreme time pressure

as the key issues behind the various inconsistencies, adding that presentation, session, or interactivity was never anticipated in the original vision of the web. Some examples of the inconsistencies include:

document.all, a Microsoft only feature,

the fact that name and id used to be interchangeable.

the different functions on retrieving nodes:

document.getElementById(id),

document.getElementsByName(name),

*node*.getElementsByTagName(tagName))

and continues with a few more examples, mostly targeting traversing the DOM, memory leaks, and event trickling and bubbling. There is a summary slide, titled "The Cracks of DOM" that summarizes:

The DOM buglist includes all of the bugs in the browser.

The DOM buglist includes all of the bugs in all supported browsers.

No DOM completely implements the standards.

Much of the DOM is not described in any standard.

In short, it's a messy, messy API. It might seem like nitpicking, but you have to keep in mind that when you are developing for the web, you rarely get to pick the browser your customers will use. Having to test everything in at least two versions of each of the major browsers gets old very soon. An API is supposed to be consistent and the DOM was a victim of the browser wars, but it's getting better. It's still not as platform neutral as the W3C (and I think all of us) would like it to be, but browser vendors seem quite more eager to co-operate than they were five or ten years ago.

Title: What's so bad about the DOM?


答:
Since you are new to the relevant technology and unfamiliar with the existing poor-quality code base you will be required to work on, it is likely that the estimation may vary to some extent in both directions. But let the client know about the latter reason :-P

First, list the myriad of changes/features your client has asked. For each requirement, do a little code review and research about how to implement and test it. You should invest this time without return before giving an estimate.

Second, make 3 columns for estimation - best case (25% probability), average case (50%), worst case (75%). For the 2 reasons mentioned in the first paragraph, you may choose the worst case estimation. You may then add even 20% buffer time. For example, for a particular requirement, your best case estimation is 2 days, average case is 4 days and worst case is 5 days. Adding 20% buffer time, your estimation is 6 days.

Third, do not give a fixed point of estimation, rather a range. For the above example, you can tell the client that the estimation is 4 to 6 days. Your client may insist on estimation for whole list of changes. In that case, you may add up the  minimums and maximums of ranges for all requirements. Then provide a final estimation in range, say 5 to 6.5 months. This has the following advantage: you may exceed estimation for one requirement, but may finish another requirement earlier. In total, they cancel out each other and final estimation holds up.

Fourth, as you finish each user requirement and deliver incrementally, review your previous estimations for each requirement. This is a continuous process and you should adjust/refine the estimation as you proceed with the project and your experience grows. If you see that difference between your refined estimation and your initial estimation is out of control, sit with your client immediately and discuss the matter.

I learned these things from the book "Software Estimation : Demystifying the Black Art" by Steve McConnell. I am grateful to him.

Title: Estimating Cost of modifying someone elses code

Body:
I am relatively new to web development and haven't had to provide estimates for many large projects yet (my last large project was just paid for by the hour without a strict deadline or budget).

A client is asking me to provide a cost and time estimate for providing a myriad of changes to another developers code for a website (php/mysql backend).

Can anyone provide some advice or links on how to go about analyzing and estimating this? The code is horrible (the website was originally outsourced to india years and years ago) and it's hard to know if I'm going to suddenly hit hurdles and blow my estimates out of the water.


答:
DOM is a terrible API

That is WRONG. DOM is NOT a terrible API.

First, remember that DOM is language agnostic. All major languages have implemented the API. This is because you just don't use it in browser, but everywhere you need to deal with XML.

Second, note that DOM does not define classes but interfaces. This has a very important implication: languages can implement it the way it suits their constructs and philosophy. This frees all the languages from having to be consistent in implementation with others.

Third, DOM is one of the two major ways to parse XML (other being SAX), and depending on your context, DOM can be very efficient.

What you are referring to is browser DOM. And, I agree that DOM "feels" bad in the browser. Part of the reason is browser incompatibilities. But, I disagree that they are the sole reason for DOM's bad reputation in the browser.

First, if you think about it, DOM is one of those areas where these incompatibilities are relatively easier to overcome. In comparison, events, for example are lot tricker and annoying to normalize.

Second, feature detection for DOM features is simpler than for other areas.

Third, DOM 3 is way better -- and today all browsers support most of it.

Certainly, incompatibilities are annoying, but when you get down to them, DOM is lot less irritating.

I also disagree with reasons like Proprietary traps, Corporate warfare, etc. being the reason for it.

I think it's the disconnect between the philosophy of JavaScript being a lightweight language, and the implementation of DOM being inspired from Java -- that has contributed to much of the frustration.

Secondly, DOM has been designed for XML, and it has been adapted for HTML. Hence in the browser, we have exactly two DOMs -- HTML DOM and the XML DOM -- and they are incompatible.

Third, DOM traversal in the browser is not good. We don't have XPath for HTML DOM, so before CSS selector engines, it was really tedious to do traversals.

Finally, I think today, with the modern browsers, (and with older browsers slowly fading away) there is no reason DOM needs to be called bad. It's certainly going to get better in browser -- both the API and the implementation.

Title: What's so bad about the DOM?

Body: I keep hearing people (Crockford in particular) saying the DOM is a terrible API, but not really justifying this statement. Apart from cross-browser inconsistencies, what are some reasons why the DOM is considered to be so bad?</p>


问:
variable comparison without initialising
I am working with a project in VC++ which involves co-ordinate system having x,y,z axis.

I am trying to check for if a variable(Point with x,y,z values) is assigned on the coordinate system or its a default point(uninitialized) .

Since a coordinate system I cannot assign a default value to the variable to be either negative or positive  or even zero since all these are valid values.

My approach over here is to have a Boolean variable associated with my Point variable. If the Boolean is set then Point assigned else not. Now I have to check for each and every statement where the value can be assigned and set the Boolean.

Now I tried with this approach which is pretty bad and you may consider it as wrong. What I am doing here is taking an uninitialized float variable (since x,y,z members of Point are float) and comparing it with x,y,z members of Point variable.

Since in the case where Point is uninitialized both float variable and members of Point match and I can declare its uninitialized. I have tried to test this on different compilers and I get the result as expected.

Obvious I get a compiler warning for uninitialized variable used for comparison

My question, Is the second approach really bad or is there any workarounds over this.

答:
Why not use boost::optional or similar functionality?

```<code>boost::optional<point> point;

if(point)
    //is init.
</code>```

You could make your own template class, but having a separate bool flag is not very good, since it clutters the namespace in every place you want a 'nullable' point. It is also not semantically obvious that the point and the bool are grouped/belong together - especially if multiple people view the code at different points in development etc.

Putting it in the point class is not 100% semantically correct imo - its better to use composition to represent this kind of thing, since a point is a point. If you layer it with a templated 'holder' that groups the bool together with the it is obvious what happens - and other places where you simply need a point, you use the Point as-is.

Body:
Why not use boost::optional or similar functionality?

boost::optional<point> point;

if(point)
    //is init.

You could make your own template class, but having a separate bool flag is not very good, since it clutters the namespace in every place you want a 'nullable' point. It is also not semantically obvious that the point and the bool are grouped/belong together - especially if multiple people view the code at different points in development etc.

Putting it in the point class is not 100% semantically correct imo - its better to use composition to represent this kind of thing, since a point is a point. If you layer it with a templated 'holder' that groups the bool together with the it is obvious what happens - and other places where you simply need a point, you use the Point as-is.


问:
Usage of Pirated software at a company
I started to work at a company as an engineer a couple of months ago. It's a small company and what they basically do is answering service on phones. Now they are switching from normal phones to IP phones so that computers take more important place in the work.

However, all the computers used by workers are equipped with pirated software, including their operating systems. Moreover, they didn't even buy one license to make copies for other computers. In other words, they did not spend any money for the software in office. I am not saying copying a licensed one is legit, but the situation is too much.

There is one guy who installed the pirated software. He does not feel any sense of guilt and even justified when I asked about it. He is not even a specialist. He just searched on the internet to install pirated software. Our boss does not have any knowledge of computers, so he took the cheaper way.

What do you think about this? Since I am still new to the company, I am not doing maintenance on those cracked computers. But I have to use those software daily. And later on I will be doing support, help desk kind of stuff. I really don't want to take responsibility for operating pirated software. From an aspect of developer and engineer, pirated software is not able to get legal support and it may work unexpectedly. So, I am thinking about changing jobs.

Am I thinking too much? Should I wait until I have more credibility with the boss and try to change his policy? So far, the boss does not take any words from me. Any opinions are welcome. Thank you

答:
Realistically, you probably want to have a conversation with the boss about this. The last thing you want is to be accused of knowing about the pirated software and not doing anything about it. So, try and find a way to chat to the boss, and educate him about what's going on, and the policy that is implicitly in operation.

If the response is that he's fine with the use of pirated software, you've done your job. The only thing remaining is to decide whether it bothers you sufficiently for you to leave.

ContentLicense: CC BY-SA 2.5

Title: Usage of Pirated software at a company


答:
From a client perspective, if you have a C/C++ program and you want to use it to talk to the internet you'd use libcurl. It's pretty much a standard (and comprehensive) library to connect to http urls to send and receive data. There are several other libraries - Microsoft has a few, there's a several open source ones.

Now that's for plain old URLs over http (or SMTP, or FTP, or Gopher, or.. libcurl is very comprehensive!) If you're trying to consume web services over SOAP, then you can use one of many other libraries such as gsoap.

For the server side, you need a webserver or framework that exposes your C++ code. Again there are many way to do this - the earliest web programs were all C/C++, written as CGI programs where the webserver called your app using a form of IPC. Since then, we have Wt, Qt, cppCMS, ffead, and all the ones from Microsoft (ISAPI, ATLServer, and now Casablanca).

I think the reason no-onne really uses C++ for their web progrmaming is because the other languages come pre-packaged with these libraries. C++ (as always) you have to go find a library to use, whereas PHP just comes ready to go for the web.


问:
I don't know C. And why should I learn it?
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.

答:
The advantage to knowing C is that you have a very good idea of how a computer works. Not just how your programming model works, but how memory's laid out, and suchlike.

The only level below C is the assembly spoken by a particular CPU.

(I'd add that knowing C also lets you appreciate how much less work you have to do in a higher level language. And hopefully an appreciation of the cost involved in working in that higher level language.)


问:
Testing an IRC Bot
I'm using Autumn gem to create a Ruby IRC bot for a game. However, it makes me feel rather embarrassed because I don't know how to test this kind of program...

I think I should mock the IO process to have a control over it but I can't see how in this case when using the gem.

Has anyone an idea ?

答:
It is very, very difficult to test external dependencies in an automated repeatable fashion. At least without creating more framework to fake the external dependency than you've got code under test. And oftentimes that sort of thing is very fragile anyhow, leading to lots of false test failures.

I'm not a rubyist by any stretch of the measure, the following advise is going to be pretty language agnostic. What I would do here is to:

Wrap the external dependency in my own interface. All my code should talk to this interface.  and not patch directly to the library. Depending on the complexity of what the return data was, I would consider building my own DTO objects as well.

Test my code against mocked or stubbed versions of this interface to ensure my end of the world is behaving correctly given correct inputs.

Finally, try and find a way to test my pass-through interface to the external service. But at the end of the day this class tends to be so simple as to be not worth the effort.

But trying to unit test external services in a conventional sense can be maddening and horribly noneffective.

PS: I should add I just wrote an IRC bot over the last weekend. I did largely use TDD in C#, and I most certainly did not test the IRC connection angle outside of using nUnit as a harness to stand up the experimental code I needed to understand how the library works.

Title: Testing an IRC Bot


答:
It is certainly a viable strategy, but it's not a silver bullet.

Pros:

if done right, applications developed this way are very responsive

you have a clear separation of logic (on the server) and presentation (on the client); the server doesn't have to concern itself at all with the presentational aspects of the application

potentially more efficient use of network bandwidth (you are only sending raw data, no presentational boilerplate)

easier to develop desktop-like GUIs, since you're less dependent on the request/response paradigm

Cons:

you have to write your client code in Javascript, or a language that can compile to Javascript, because that's the only thing available in a browser

resource usage on the client may be higher, so the application may not work well on substandard devices (think mobile browsers etc.)

it won't work at all with javascript disabled; if it is have a public-facing website, you have to think hard whether you are willing to take this risk (especially if you consider SEO and accessibility - a javascript-heavy approach is usually devastating on these two fronts)

a lot of logic has to be written twice: once on the client, and once again on the server (because you can never trust the client)

concurrency can be a hell, so you need to design your client-side code very carefully and be prepared for all sorts of concurrency issues

Title: Pros and cons of an HTML/JavaScript only web app

Body:
I come from an ASP.NET forms background and have found server side coding very powerful in the past. More recently, however, I have been wanting to phase out the server side code of the front-end and replace it with pure HTML/JavaScript, which accesses the data through JSON webservices. I have no real experience in this, and so I would like to hear whether this is a tried and tested model. Also, what are the pitfalls surrounding it?

I find ASP.NET user controls very useful, so I would like to keep the theory behind it by storing markup templates in separate HTML files on the server. These will be retrieved and used through jQuery AJAX and the jQuery HTML templates plugin respectively.

Any input will be extremely appreciated.

P.S. Sorry for the noob question, but is this type of Web architecture what is referred to as web-2.0 or am I completely off-track?


答:
Look to how similar industries do it. An architect wouldn't give an accurate estimate on a garage extension without having seen the property first.

Charge them an investigation fee for your initial time. Explain that the code is in a state where you can't possibly give them an accurate estimate without looking deeper at the current situation. Make sure they get something at the end of it, as a mark of faith, some documentation they could give to another developer if they chose to, to save them having to do the same work.

And then, if it's important to you that you get the actual development work, tell them that if they come to you for the actual development work, you'll knock 50% or even 100% of that charge off the final bill. You can't lose and people do so like to get something for free.


问:
Build functionality around the design, or the other way around?
When you build an application, is it better to design the UI first (in Photoshop or whatever), then implement the functionality following the UI you just designed, or do the programming and build the design as you go?

Advantages I see using UI as reference:

the app will end up very UI-friendly :)

like pdr mentioned, if working for a client, he gets exactly what he imagined

Disadvantages:

the programming will get more complicated, so development time increases

any others? :D

答: I've found you often need to do both in parallel.  for example, the UI might dictate that you need a web API for AJAX interaction, or a certain structure for pages.  on the other hand, you will need to design how your lower tier will access data and provide services.  then the fun part is creating the controllers to wire them all up.</p>


答:
If you have any customer engagement whatsoever, work the UI first, show it to them, change it a few times (from what they asked for to what they really want), then write the back-end. This saves you the time of writing, and then rewriting, and then rewriting again, the entire stack.

If you don't have that customer engagement, it really doesn't make much difference in my experience.

I should mention though that I am not recommending writing the entire UI before writing the back end. Everything should be done one behaviour at a time, so that there is always a working application to demonstrate, even if it lacks a lot of expected behaviour.

Title: Build functionality around the design, or the other way around?

Body:
When you build an application, is it better to design the UI first (in Photoshop or whatever), then implement the functionality following the UI you just designed, or do the programming and build the design as you go?

Advantages I see using UI as reference:

the app will end up very UI-friendly :)

like pdr mentioned, if working for a client, he gets exactly what he imagined

Disadvantages:

the programming will get more complicated, so development time increases

any others? :D


问:
API design and versioning using EJB
I have an API that is EJB based (i.e. there are remote interfaces defined) that most of the clients use.  As the client base grows there are issues with updates to the API and forcing clients to have to update to the latest version and interface definition.

I would like to possibly look at having a couple versions of the API deployed at a time (i.e. have multiple EAR files deployed with different versions of the API) to support not forcing the clients to update as frequently.  I am not concerned about the actual deployment of this, but instead am looking for thoughts and experiences that others have on using EJB's as an API client.

How do you support updating versions, are clients required to update?

Does anyone run multiple versions in a production environment?  Are there pro's cons?

Any other experiences or thoughts on this approach, and having an EJB centric API?

答: You can use the same EAR and just have different JNDI names for the different versions of your EJB.  Then the old clients can still connect to the old EJB using the old client libs and new clients can connect to the new client libs.  As Martijn pointed you don't want to have too many different versions floating around because that will greatly complicate support.</p>

Title: API design and versioning using EJB


问:
How were some language communities (eg, Ruby and Python) able to prevent fragmentation while others (eg, Lisp or ML) were not?
The term "Lisp" (or "Lisp-like") is an umbrella for lots of different languages, such as Common Lisp, Scheme, and Arc. There is similar fragmentation in other language communities, like in ML.

However, Ruby and Python have both managed to avoid this fate, where innovation occurred more on the implementation (like PyPy or YARV) instead of making changes to the language itself.

Did the Ruby and Python communities do something special to prevent language fragmentation?

答:
They're essentially all implementation defined languages

When it is easy to create a new implementation of a language that is largely compatible with existing code, then hackers being hackers, they go ahead and do it. Everyone writes a Lisp implementation at some point. ML compilers are almost mandatory for grad students in language design -- the language is after all famously well documented.

On the other hand we have the ad hoc and implementation-defined languages. Or languages that are just so complex that it is a signficant barrier to ever producing a viable alternative implementation:

ruby; perl; python -- all too implementation-defined to produce viable alternatives

ghc haskell and erlang -- well defined, but so hard to do anything that competes with ghc (or erlang) that people don't usually bother

This seeming downside -- languages that are too hard to produce viable alternatives to, have the massive upside: scarce developer resources are concentrated on the one true implementation.

As a historical note, several in the Haskell community actively pursued mergers and concentration of dev effort, recognizing that any splintering of the dev community would mean we'd not succeed. GHC was chosen and championed.


答:
It really depends on the kind of application you are going to develop. But let's assume you are going to create a rather complex UI with lots of functionality, then having a clear concept first, written down on a piece of paper or as a sketch in some kind of drawing program, will help you to get it right.

That does not mean you should implement that UI as a whole before starting to implement functionalites at a time. Better implement only as much of it as you need to make a certain functionality work (scrum people would perhaps call it a "user story"). Use your "Photoshop UI" as a rough guide or "vision" how the final UI will look like in the end, but not more.

Disadvantages:
      the programming will get more complicated, so development time increases

What makes you think that? Following no plan will make things more complicated, especially on the long term, that is my experience.


问:
Should one check for null if he does not expect null?
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.

The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?

On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.

On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X".

What practice do you follow and what are your arguments for or against either approach?

Update:

I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load.

Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently.

The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing?

答: Fail early, fail often. null is one of the best unexpected values you can get, because you can fail quickly as soon as you try to use it. Other unexpected values are not so easy to detect. Since null automatically fails for you whenever you try to use it, I would say that it does not require an explicit check.


答: IMHO trying to handle null values that you don't expect leads to overly complicated code. If you don't expect null, make it clear by throwing ArgumentNullException. I get really frustrated when people check if the value is null and then try to write some code that doesn't make any sense. The same applies to using SingleOrDefault (or even worse getting collection) when someone really expects Single and many other cases when people are afraid (I don't really know of what) to state their logic clearly.

Title: Should one check for null if he does not expect null?

Body:
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.

The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?

On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.

On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X".

What practice do you follow and what are your arguments for or against either approach?

Update:

I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load.

Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently.

The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing?


答:
The habit of checking for null to my experience comes from former C or C++ developers, in those languages you have a good chance of hiding a severe error when not checking for NULL. As you know, in Java or C# things are different, using a null ref without checking for null will cause an exception, thus the error will not be secretly hidden as long as you don't ignore it on the calling side. So in most cases, checking explicitly for null does not make much sense and overcomplicates the code more than necessary. That's why I don't consider null checking to be a good habit in those languages (at least, not in general).

Of course, there are exceptions from that rule, here are those I can think of:

you want a better, human-readable error message, telling the user in what part of the program the wrong null reference occured. So your test for null throws just a different exception, with a different error text. Obviously, no error will get masked that way.

you want to make your program "fail more early". For example, you want to check for a null value of a constructor parameter, where the object reference otherwise would only be stored in a member variable and used later.

you can deal with the situation of a null ref safely, without the risk of subsequent faults, and without masking a severe error.

you want a completely different kind of error signaling (for example, returning an error code) in your current context


答:
A language is a tool.  If you only have to write web pages and the like then I am sure that you can get away without having to learn C, in just the same way that if you only ever make plastic model kits you only need a sharp knife and glue, a spanner is not normally required.

I write code for embedded systems with highly restricted memory resources (the biggest I have done recently is 16kbyte and that was HUGE)  In this market then C or assembler are the only options and any of the fluffy higher level languages just don't work.

Title: I don't know C. And why should I learn it?

Body:
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.


问:
Creating webservices using spring-mvc. One project or multiple projects
Using spring mvc to create a restful api, Maven is build tool and tomcat with spring jars is deployment .

Plan A: each webservice will be its own separate war file/project ?  if required I would supply dependices as jar(s) (such as any dao's/dto's/service layer classes used in different webservices? I would share the spring jars between projects from with tomcat lib directory.

Plan B: Have one large project with different controllers (and subsequent request mappings for restful api) added when needed. Supply the spring dependices with project in maven.

Which is better ? I'm aware spring is not jax-rs compliant - what does this mean in practice, whats the difference if not compliant ?

答: It depends on how you want these web services to scale. For example, if your 4 GET calls are called 1 million more times per day than the 1 PUT request, then you'll want to split them out so you can load balance them more easily.</p>

OwnerDisplayName: NimChimpsky


问:
Estimate cost of project depends on [SLOC|COCOMO]?
Is it logical to estimate cost of project depends on source lines of code?

Like those calculated reports from tools such as

sloccount

ohloh estimating

*

How to convince [somebody|employer|client] to pay depends on those reports ?
The weird things come to scene when I see something like $83,862 based on my project.

Sometimes the developer [him|her]self would write more lines of code because of this estimating.

So if the count of the source lines isn't worthy, Why should be [sometimes|somehow] interesting part of development, Specially for employer, It does amaze them but why doesn't have any effect on pricing ?

Hey Employer I've developed this project that worth $1 million dollars, This source code counter program will prove it.

Maybe I don't know the real worth of my work, Should I public it for people and collect some comments about it or show it to some [experts|consultants] to find-out or just estimate myself upon my knowledge, And all of these solutions aren't right or at least logical.

And what happens to those codes I didn't wrote by myself, I mean sometimes we just copy a piece of code and [pasted|modified] into project.

And if estimating in this way is wrong, What is the purpose of these tools to generate such a report about source lines of code, Average hourly work and other facts.

Ohloh :

Estimated Cost

We calculate the estimated cost of the project using the Basic COCOMO
  model. For those familiar with the details, we are using coeffcients
  a=2.4 and b=105.

Estimate still seems way off?

Software cost estimation is tricky business even when all the
  variables are known (which we certainly don't have). One thing to
  remember is that COCOMO was created to model large institutional
  projects, which often don't compare well with distributed open-source
  projects. Beyond just development time, COCOMO is meant to include the
  design, specification drafting, reviewing and management overhead that
  goes along with producing quality software.

This model seems to be most accurate with mature, large projects.
  Young projects with little activity are typically overvalued.

I know quote from ohloh isn't just about SLOC

答:
You should not estimate based on lines of source code. You should estimate based on the time needed to implement the necessary changes, and that comes from your own experience and extensive knowledge of your codebase.

As you mentioned, estimating based on lines of source code could mean developers purposely write more code when it isn't necessary. Why would you ruin your codebase like this?


答: The first option is good if you might deploy to different boxes in the future, for example on a high traffic site you may want each API in a separate machine or cluster. Otherwise it's just a pain so for small projects just put it all in one war file.</p>

Title: Creating webservices using spring-mvc. One project or multiple projects

Body:
Using spring mvc to create a restful api, Maven is build tool and tomcat with spring jars is deployment .

Plan A: each webservice will be its own separate war file/project ?  if required I would supply dependices as jar(s) (such as any dao's/dto's/service layer classes used in different webservices? I would share the spring jars between projects from with tomcat lib directory.

Plan B: Have one large project with different controllers (and subsequent request mappings for restful api) added when needed. Supply the spring dependices with project in maven.

Which is better ? I'm aware spring is not jax-rs compliant - what does this mean in practice, whats the difference if not compliant ?


问:
How important is self-teaching in the programming field?
I'm 16. I started programming about a year ago when I was about to start high-school. I'm going for a career in programming, and I'm doing my best to learn as much as I can. When I first started, I learned the basics of C++ from a book and I started to learn things by myself from there on. Nowadays I'm much more experienced than I was a year ago. I knew I had to study by myself because high-school won't (likely) teach me anything valuable about programming, and I want to be prepared.

The question here is: how important is it to study programming by oneself?

答:
Self-teaching is very important. You cannot rely on a formal education to teach you everything you need to know about your field. However, that being said, a formal education is also very important if you want to enter that career field well-prepared and well-equipped.

I am on my way to college and have spent the past four years teaching myself software development, as a result I now work for a large, well-known company maintaining enterprise applications. It doesn't take a ton of talent but it does take a ton of work and motivation. I think literature and practice are your best bet when it comes to learning. It is also important to pick a specific field as, though you can carry languages and logic across all fields, you can only truly become "great" given sufficient practice and understanding in a specific field.


答:
Learning on your own is very important. Having the discipline to research and gather the necessary knowledge to accomplish a task will put you far ahead of many others that rely on formal training to accomplish the same task. This goes for any industry, not just the software industry.

Don't get me wrong, getting some formal training or education is helpful, but your own motivation to better your skills will help you grow into a better software developer. There is always something to be learned: new platforms or programming languages to experiment with, development methodologies to implement, tools and algorithms to use, the list goes on. Not everything will be introduced to you through formal training and so it is up to you to learn about other topics and ideas you might be interested in that will help you throughout your career in programming.

Title: How important is self-teaching in the programming field?

Body:
I'm 16. I started programming about a year ago when I was about to start high-school. I'm going for a career in programming, and I'm doing my best to learn as much as I can. When I first started, I learned the basics of C++ from a book and I started to learn things by myself from there on. Nowadays I'm much more experienced than I was a year ago. I knew I had to study by myself because high-school won't (likely) teach me anything valuable about programming, and I want to be prepared.

The question here is: how important is it to study programming by oneself?


答:
I would consider the question from the point of view of semantics, i.e. ask myself what a NULL pointer or a null reference argument represents.

If a function or method foo() has an argument x of type T, x can be either mandatory or optional.

In C++ you can pass a mandatory argument as

A value, e.g. void foo(T x)

A reference, e.g. void foo(T& x).

In both cases you do not have the problem of checking a NULL pointer. So, in many cases, you do not need a null pointer check at all for mandatory arguments.

If you are passing an optional argument, you can use a pointer and use the NULL value to indicate that no value was given:

```<code>void foo(T* x)
</code>```

An alternative is to use a smart pointer like

```<code>void foo(shared_ptr<T> x)
</code>```

In this case, you probably want to check the pointer in the code, because it makes a difference for method foo() whether x contains a value or no value at all.

The third and last case is that you use a pointer for a mandatory
argument. In this case, calling foo(x) with x == NULL is an error and
you have to decide how to handle this (the same as with an
out-of-bounds index or any invalid input):

No check: if there is a bug let it crash and hope this bug appears early enough (during testing). If it doesn't (if you fail to fail early enough), hope that it won't appear in a production system because the user experience will be that they see the application crash.

Check all arguments at the beginning of the method and report invalid NULL arguments, e.g. throw an exception from foo() and let some other method handle it. Probably the best thing to do is to show the user a dialog window saying that the application has encountered an internal error and is going to be closed.

Apart from a nicer way of failing (giving the user more information), an advantage of the second approach is that it is more likely that the bug will be found: the program will fail every time the method is called with the wrong arguments whereas with approach 1 the bug will only appear if a statement dereferencing the pointer is executed (e.g. if the right branch of an if statement is entered). So approach 2 offers a stronger form of "fail early".

In Java you have fewer choices because all objects are passed using references which can always be null. Again, if the null represents a NONE value of an optional argument, then checking the null will (probably) be part of the implementation logic.

If the null is an invalid input, then you have an error and I would apply similar considerations as for the case of C++ pointers.
Since in Java you can catch null pointer exceptions, approach 1 above is equivalent to approach 2 if method foo() dereferences all input arguments in all execution paths (which probably occurs very often for small methods).

Summarizing

Both in C++ and Java, checking if optional arguments are null is part of the program's logic.

In C++, I would always check mandatory arguments to ensure that a proper exception is thrown so that the program can handle it in a robust way.

In Java (or C#), I would check mandatory arguments if there are execution paths that won't throw in order to have a stronger form of "fail early".

EDIT

Thanks to Stilgar for more details.

In your case it seems that you have null as the result of a method. Again, I think you should first clarify (and fix) the semantics of your methods before
you can take a decision.

So, you have method m1() calling method m2() and m2() returns a reference
(in Java) or a pointer (in C++) to some object.

What is the semantics of m2()?
Should m2() always return a non-null result? If this is the case, then a null result is an internal error (in m2()).
If you check the return value in m1() you can have a more robust error handling. If you don't, you will probably have an exception, sooner or later. Maybe not. Hope that the exception is thrown during testing and not after deployment. Question: if m2() should never return null, why is it returning null? Maybe it should throw an exception instead? m2() is probably buggy.

The alternative is that returning null is part of the semantics of method m2(), i.e. it has an optional result, which should be documented in the the Javadoc documentation of the method. In this case it is OK to have a null value. Method m1() should check it as any other value: there is no error here but probably checking if the result is null is just part of the program logic.

Body:
I would consider the question from the point of view of semantics, i.e. ask myself what a NULL pointer or a null reference argument represents.

If a function or method foo() has an argument x of type T, x can be either mandatory or optional.

In C++ you can pass a mandatory argument as

A value, e.g. void foo(T x)

A reference, e.g. void foo(T& x).

In both cases you do not have the problem of checking a NULL pointer. So, in many cases, you do not need a null pointer check at all for mandatory arguments.

If you are passing an optional argument, you can use a pointer and use the NULL value to indicate that no value was given:

void foo(T* x)

An alternative is to use a smart pointer like

void foo(shared_ptr<T> x)

In this case, you probably want to check the pointer in the code, because it makes a difference for method foo() whether x contains a value or no value at all.

The third and last case is that you use a pointer for a mandatory
argument. In this case, calling foo(x) with x == NULL is an error and
you have to decide how to handle this (the same as with an
out-of-bounds index or any invalid input):

No check: if there is a bug let it crash and hope this bug appears early enough (during testing). If it doesn't (if you fail to fail early enough), hope that it won't appear in a production system because the user experience will be that they see the application crash.

Check all arguments at the beginning of the method and report invalid NULL arguments, e.g. throw an exception from foo() and let some other method handle it. Probably the best thing to do is to show the user a dialog window saying that the application has encountered an internal error and is going to be closed.

Apart from a nicer way of failing (giving the user more information), an advantage of the second approach is that it is more likely that the bug will be found: the program will fail every time the method is called with the wrong arguments whereas with approach 1 the bug will only appear if a statement dereferencing the pointer is executed (e.g. if the right branch of an if statement is entered). So approach 2 offers a stronger form of "fail early".

In Java you have fewer choices because all objects are passed using references which can always be null. Again, if the null represents a NONE value of an optional argument, then checking the null will (probably) be part of the implementation logic.

If the null is an invalid input, then you have an error and I would apply similar considerations as for the case of C++ pointers.
Since in Java you can catch null pointer exceptions, approach 1 above is equivalent to approach 2 if method foo() dereferences all input arguments in all execution paths (which probably occurs very often for small methods).

Summarizing

Both in C++ and Java, checking if optional arguments are null is part of the program's logic.

In C++, I would always check mandatory arguments to ensure that a proper exception is thrown so that the program can handle it in a robust way.

In Java (or C#), I would check mandatory arguments if there are execution paths that won't throw in order to have a stronger form of "fail early".

EDIT

Thanks to Stilgar for more details.

In your case it seems that you have null as the result of a method. Again, I think you should first clarify (and fix) the semantics of your methods before
you can take a decision.

So, you have method m1() calling method m2() and m2() returns a reference
(in Java) or a pointer (in C++) to some object.

What is the semantics of m2()?
Should m2() always return a non-null result? If this is the case, then a null result is an internal error (in m2()).
If you check the return value in m1() you can have a more robust error handling. If you don't, you will probably have an exception, sooner or later. Maybe not. Hope that the exception is thrown during testing and not after deployment. Question: if m2() should never return null, why is it returning null? Maybe it should throw an exception instead? m2() is probably buggy.

The alternative is that returning null is part of the semantics of method m2(), i.e. it has an optional result, which should be documented in the the Javadoc documentation of the method. In this case it is OK to have a null value. Method m1() should check it as any other value: there is no error here but probably checking if the result is null is just part of the program logic.


答:
Estimating based off LOC's is purposefully bad and I thought the industry as a whole had moved on from it.

However you as a developer should know how to price for your own worth, if you have to justify to a client why it's cost  for a specific feature then that's what you'll have to do.

Clients/bosses are overly interested in what they're getting at a low level (in general), they care about the result. For them either the result is worth  and they're happy to pay it because it achieves , or it achieves  but they think it was more money than  was worth.

And rounding back, telling a client how many lines of code there is in a product might make them go "oh cool!" and not change the price as it's totally abstract. Ford will tell you there's 160bhp in your Fiesta and make you go "oh cool!" but you won't throw them another £5k.

Title: Estimate cost of project depends on [SLOC|COCOMO]?

Body:
Is it logical to estimate cost of project depends on source lines of code?

Like those calculated reports from tools such as

sloccount

ohloh estimating

*

How to convince [somebody|employer|client] to pay depends on those reports ?
The weird things come to scene when I see something like $83,862 based on my project.

Sometimes the developer [him|her]self would write more lines of code because of this estimating.

So if the count of the source lines isn't worthy, Why should be [sometimes|somehow] interesting part of development, Specially for employer, It does amaze them but why doesn't have any effect on pricing ?

Hey Employer I've developed this project that worth $1 million dollars, This source code counter program will prove it.

Maybe I don't know the real worth of my work, Should I public it for people and collect some comments about it or show it to some [experts|consultants] to find-out or just estimate myself upon my knowledge, And all of these solutions aren't right or at least logical.

And what happens to those codes I didn't wrote by myself, I mean sometimes we just copy a piece of code and [pasted|modified] into project.

And if estimating in this way is wrong, What is the purpose of these tools to generate such a report about source lines of code, Average hourly work and other facts.

Ohloh :

Estimated Cost

We calculate the estimated cost of the project using the Basic COCOMO
  model. For those familiar with the details, we are using coeffcients
  a=2.4 and b=105.

Estimate still seems way off?

Software cost estimation is tricky business even when all the
  variables are known (which we certainly don't have). One thing to
  remember is that COCOMO was created to model large institutional
  projects, which often don't compare well with distributed open-source
  projects. Beyond just development time, COCOMO is meant to include the
  design, specification drafting, reviewing and management overhead that
  goes along with producing quality software.

This model seems to be most accurate with mature, large projects.
  Young projects with little activity are typically overvalued.

I know quote from ohloh isn't just about SLOC


答:
I don't agree that you need to learn C first, but I do believe you should learn C eventually.  All abstractions are leaky and understanding C makes it easier to understand what's really happening when you use some fancy high-level abstraction.  That said, I also think all serious programmers should eventually learn to at least read assembler, for the same reason.

Learning these low-level concepts gives surprising ability to reason about high-level stuff.  For example, in C++ and D, default arguments to virtual functions are determined by the static (compile time) type of the object, not the dynamic (runtime) type.  This makes no sense unless you understand how vtables and calling conventions work and why it would be extremely hard to implement virtual functions in the opposite way.


答: Self instruction is an indispensable skill for a programmer to have.  Too many do not.  If you're good, you'll use this skill for the rest of your career.</p>


答:
Disadvantages:

the programming will get more complicated, so development time
  increases

There's no reason why this has to be true.


答: Self-study is very important because you won't always have opportunities for formal training. When you start looking for a project, internship or job, find ones that have solid senior developers who can really teach you something. Being in an environment that does things right can be the express route to quality code.</p>


答:
The question is not so much whether you should check for null or let the runtime throw an exception; it is how you should respond to such an unexpected situation.

Your options, then, are:

Throw a generic exception (NullReferenceException) and let it bubble up; if you don't do the null check yourself, this is what happens automatically.

Throw a custom exception that describes the problem on a higher level; this can be achieved either by throwing in the null check, or by catching a NullReferenceException and throwing the more specific exception.

Recover by substituting a suitable default value.

There is no general rule which one is the best solution. Personally, I would say:

The generic exception is best if the error condition would be a sign of a serious bug in your code, that is, the value that is null should never be allowed to get there in the first place. Such an exception may then bubble all the way up into whatever error logging you have set up, so that someone gets notified and fixes the bug.

The default value solution is good if providing semi-useful output is more important than correctness, such as a web browser that accepts technically incorrect HTML and makes a best effort to render it sensibly.

Otherwise, I'd go with the specific exception and handle it somewhere suitable.


答:
Checking for a null should be your second nature

Your API will be used by other people and their expectation is likely to be different from yours

Thorough unit tests normally highlight a need for a null reference check

Checking for nulls doesn't imply conditional statements. If you worry that null checking makes your code less readable, then you may want to consider .NET code contracts.

Consider installing ReSharper (or similar) to search your code for missing null reference checks


答:
Use asserts to test and indicate pre/postconditions and invariants for your code.

It makes it so much easier to understand what the code expects and what it can be expected to handle.

An assert, IMO, is a suitable check because it is:

efficient (usually not used in release) ,

brief (usually a single line) and

clear (precondition violated, this is a programming error).

I think self-documenting code is important, therefore having a check is good. Defensive, fail-fast, programming makes maintenance way easier, which is where usually most time is spent.

Update

Wrt your elaboration. It's usually good to give the end user an application that works well under bugs, i.e. shows as much as possible. Robustness is good, cause heaven only knows what will break at a critical moment.

However , developers & testers must be aware of bugs ASAP, so you probably want a logging framework with a hook that can display an alert to the user that there was a problem. The alert should probably be shown to all users, but can probably be tailored differently depending on the runtime environment.


答:
Is there anything that prevents you from requiring coordinates when initializing the Point?  The class might look something like:

```<code>class Point {
public:
    Point( float x, float y, float z )
        : _x( x ), _y( y ), _z( z ) {}

    // Getters/setters as needed

private:
    float _x, _y, _z;
}
</code>```

At this point, there's no way to create the object without having an initial value, which is presumably valid.

With this approach, if you need uninitialized Point variables somewhere, you will need to use pointers.  If you follow the common practice of initializing pointers to NULL (or nullptr), whenever you have a valid pointer to a Point, you have a valid set of coordinates.

Title: variable comparison without initialising

Body:
I am working with a project in VC++ which involves co-ordinate system having x,y,z axis.

I am trying to check for if a variable(Point with x,y,z values) is assigned on the coordinate system or its a default point(uninitialized) .

Since a coordinate system I cannot assign a default value to the variable to be either negative or positive  or even zero since all these are valid values.

My approach over here is to have a Boolean variable associated with my Point variable. If the Boolean is set then Point assigned else not. Now I have to check for each and every statement where the value can be assigned and set the Boolean.

Now I tried with this approach which is pretty bad and you may consider it as wrong. What I am doing here is taking an uninitialized float variable (since x,y,z members of Point are float) and comparing it with x,y,z members of Point variable.

Since in the case where Point is uninitialized both float variable and members of Point match and I can declare its uninitialized. I have tried to test this on different compilers and I get the result as expected.

Obvious I get a compiler warning for uninitialized variable used for comparison

My question, Is the second approach really bad or is there any workarounds over this.

Body:
Is there anything that prevents you from requiring coordinates when initializing the Point?  The class might look something like:

class Point {
public:
    Point( float x, float y, float z )
        : _x( x ), _y( y ), _z( z ) {}

    // Getters/setters as needed

private:
    float _x, _y, _z;
}

At this point, there's no way to create the object without having an initial value, which is presumably valid.

With this approach, if you need uninitialized Point variables somewhere, you will need to use pointers.  If you follow the common practice of initializing pointers to NULL (or nullptr), whenever you have a valid pointer to a Point, you have a valid set of coordinates.


答: In programming, self-teaching is what you will be doing every day. You will have to teach yourself a lot of things, not just computer languages and tools that keep on changing. You will have to learn code other people wrote and you will have to fix that too with minimal instruction and supervision. It is rare in some organizations to get any real training more than 1 time a year (if ever!). Make sure you can do (and enjoy) this, otherwise, consider a different career while you are still young.</p>


答:
It's critical.  I don't think I've ever known a good programmer who wasn't self-taught at some level.  As a hiring manager at a large company, I can say that a candidate who describes personal projects and a desire to learn will trump one with an impressive degree every time.  (Though it's best to have both.)

Here's the thing about college:  Computer Science courses teach theory, not technology.  They will teach you the difference between a hash table and a B-tree, and the basics of how an operating system works.  They will generally not teach you computer languages, operating systems or other technologies beyond a shallow level.

I remember back in the mists of time when I took my first data structures class and we got a thin manual for this new language called "C++" that they'd decided to start learning.  We had two weeks to pick it up enough to write code.  That was a good lesson in and of itself.  That's the way your career will go.

Your school will likely not teach you what you need to get a good job.  Schools often trail what's hot in the industry by many years.  Then you'll get a job.  Whatever company you go to will almost certainly not spend any particular effort to train you.  The bad companies are too cheap, and frankly the good companies will only hire people smart enough to pick it up as they go.

I graduated college in 1987.  I went to work as a C programmer with expertise in DOS, NetBIOS and "Terminate-and-Stay-Resident" programs.  In the years since, I have had little if any actual training.  Look at the job ads... not much call for those skills!  The only reason I can be employed today is because I've spent the intervening years constantly learning.  To succeed as an engineer, you have to have the habit of learning.  Hell, I'd go beyond that: you have to have the love of learning.  You need to be the sort of person who messes around with WebGL or Android or iOS because it looks fun.  If you are that sort of person, and maintain the habit of learning, you'll go far in the industry.


答:
A bot should be almost entirely event driven. In that case, you'll most likely have an event handler. In the case of an IRC bot, the event handler will just be reading a TCP input stream, detecting what event is happening, and then calling the event handler. If your events are built to an interface then you can quite easily fake events in your automated tests.

This all comes down to how Autumn works. I'm not familiar so it may do its own event handling in which case things may get a little more tricky.

Title: Testing an IRC Bot

Body:
I'm using Autumn gem to create a Ruby IRC bot for a game. However, it makes me feel rather embarrassed because I don't know how to test this kind of program...

I think I should mock the IO process to have a control over it but I can't see how in this case when using the gem.

Has anyone an idea ?


答:
It's crucial, otherwise you'll stay behind

I learn every day, at work, here, by reading books, by asking and answering questions. The more I learn the more I understand how little I know.


答:
Whenever these types of questions come up, I always think about this article I read in paper form when it was published.  Fortunately, it has made its way to the net: http://www.dvorak.org/blog/whatever-happened-to-wordstar-2/

In particular, this quote is interesting:

In four months Barnaby wrote 137,000 lines of bullet-proof assembly
  language code. Rubenstein later checked with some friends from IBM who
  calculated Barnaby’s output as 42-man years.

According to the article, he wrote 137k lines of (implied) fairly defect-free code in four months.  Some other individuals estimated this output as 42-man years.

Estimations can combine many facets, including LOC, that can be used to "estimate" the cost in developing a system.

So the question is: Would you rather pay Barnaby for the four months that he worked on the project or the 42-man years that it was estimated to be equivalent to?

I know this isn't an exact correlation, but it's something to think about.


问:
How to apologize when you have broken the nightly build
My first commit in my project resulted in the nightly build being broken and people are all over me as we are nearing the release. I want to send an apology email that should sound sincere
and at the same time hinting that this was my first commit and this would not be repeated any more.

Being a non-native English speaker, I have difficulties coming up with correct words. Can someone please help?

答:
I would not apologise.

I would blame CI lead for allowing me commit broken build.

There should be a CI process in place for stopping developers from committing broken code.

If local build fails, then it should not be allowed to enter build server.


答:
Talent is Overrated.

It takes at least 10 years of practice before one can become great in any given area. So it is important to start early.

The fact that you started at an early stage of your life doing something you seem to like already puts you way ahead of the pack. So unless you're having second thoughts about the area you'll be working, don't stop... don't ever stop!

I consider self learning one of the best skills of any given developer and the second being a college degree. A good college degree is important just because it adds so much quality to your knowledge which you would probably not be able to gather by yourself. There are certainly exceptions to this rule, but that's all they are; exceptions.

Also, the more experience you build up early the better you'll enjoy college and the better you'll absorb new concepts presented to you. At first you'll find it all so easy and pointless but very quickly you will feel challenged and will eager to learn more.

After you leave college don't ever stop learning as it will be one of your best features. I recommend reading 'Talent is Overrated'. You can take a look at this quick article about that book:

http://www.devlounge.net/strategy/the-talent-myth


答:
Self-teaching is very important for two reasons:

after your studies : as already stated in other answers, self-teaching is what you will do in your everyday life as a developer. You cannot know everything and companies know this. What you MUST know is how to improve yourself. Best developers have the ability to learn new languages, new technologies quickly by themselves.

during your studies : the distance between what college courses will teach you and the reality of what will be your job is huge. Specifically I am talking about maintenance and maintainability. An essential part of a developer's job consists in maintaining legacy code (bug fixes, improvements, adding features, etc). You can read Is the creation of brand new software generally a major part of most programming jobs? for further details.

As maintaining legacy code is essential, you will also need to write maintainable code yourself, and this is rarely taught with formal lessons (see How to improve the training of students regarding maintainability?). If you don't practice self-teaching and read a lot during your studies, you are unlikely to acquire the needed skills that will make you a better developer than the average.

Don't try to learn lots of languages/technologies during your studies, but learn good practices and clean coding. For example you'd better read Robert C. Martin's "Clean Code" than Herbert Schildt's "Java The Complete Reference" during your studies.


答:
Better a late answer than never...

As many others have said, don't apologize for breaking the build. Simply admit that it was you and get on with the job. This stuff would happen whether you were there or not, and nobody deserves to be treated poorly because of it. People react badly under pressure, so if you are able to remain calm and simply get on with the job, you'll stand out when it matters. My advice for when people give you a hard time is to simply avoid being defensive, defuse the situation by letting people know you are either on to the problem or you are quick to seek advice if you find you've become stuck.

Personally, I see a broken build as an opportunity.

If the build breaks and you can prove it's your fault, then it's likely to show that the continuous integration and build processes are doing their jobs. This is a good thing, as it validates your processes.  If the build never breaks, I'd worry that there was something wrong with it.

If you've broken the build in a fairly common manner, and it happens to break in this way often, then perhaps something is missing from the CI process. This is an opportunity to improve your processes so that the common failure scenarios can be better managed.

If you've gone beyond the call of duty and really messed up the build with an obscure problem, then you have an opportunity to learn about something new that might be important enough to trigger a warning to the rest of the team.

So what I'm saying is that breaking the build occasionally means that people are doing their jobs.  Sure you might have made a mistake, but if you use it as an opportunity to learn, you are doing your job simply by learning to do it better next time.

Title: How to apologize when you have broken the nightly build

Body:
My first commit in my project resulted in the nightly build being broken and people are all over me as we are nearing the release. I want to send an apology email that should sound sincere
and at the same time hinting that this was my first commit and this would not be repeated any more.

Being a non-native English speaker, I have difficulties coming up with correct words. Can someone please help?


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答: I'm surprised no one has mentioned The Pragmatic Programmer. It's a must-read if you are at all interested in your craft.</p>


答:
Sure NULL is not expected, but there are always bugs!

I believe you should check for NULL whether or not you don't expect it. Let me give you examples (although they are not in Java).

In World of Warcraft, due to a bug the image of one of the developers appeared on a cube for many objects. Imagine if the graphics engine didn't expect NULL pointers, there would have been a crash, while it was turned into a not so fatal (even funny) experience for the user. The very least is, you wouldn't have unexpectedly lost your connection or any of your save points.

This is an example where checking for NULL prevented a crash and the case was silently handled.

Imagine a bank teller program. The interface does some checks and sends input data to an underlying part to perform the money transfers. If the core part expects not to receive NULL, then a bug in the interface can cause a problem in the transaction, possibly some money in the middle getting lost (or worse, duplicated).

By "a problem" I mean a crash (as in crash crash (say the program is written in C++), not a null pointer exception). In this case, the transaction needs to roll back if NULL is encountered (which of course would not be possible if you didn't check the variables against NULL!)

I'm sure you get the idea.

Checking validity of arguments to your functions doesn't clutter up your code, as that is a couple checks at the top of your function (not spread in the middle) and greatly increases robustness.

If you have to choose between "the program tells the user that it has failed and gracefully shuts down or roll back to a consistent state possibly creating an error log" and "Access Violation", wouldn't you choose the first one? That means every function should be prepared for being called by a buggy code rather than expecting everything is correct, simply because bugs always exist.


答: If you are developing an application of a line of business type, then you must tailor your application to the business flow required for each business function. There are certain GUI aspects of the application that won't be affected much by the specific functions of the application such as logon, help, backgrounds, menu styles, footers, etc. You can build the common parts in a prototype and add your functionality to that or demonstrate the functionality using BPM first, then merge it in your prototype if necessary. </p>


答:
What's wrong with the DOM? Aside from Java-inspired syntax (which
Crockford has touched on), nothing.

What's "wrong" applies partially to browser vendors; what's "wrong"
applies to developers; what's "wrong" applies to ignorance.

So, where to begin?

Down the rabbit hole…

Browser Vendors

First off, browser vendors have fought competitively over decades
to be the "best", "fastest", "easiest", etc. In the first decade
(199x—2000), Microsoft ruled the roost. Internet Explorer introduced
innovative ideas such as:

exposing the browser's HTML parsing engine as innerHTML and
outerHTML;

easy textual manipulation with innerText and outerText;

an event model (*tachEvent) that was the blueprint for DOM
Level 2 Events (*EventListener).

Each have contributed (for better and for worse) significantly to
today's web development stack. Opera even went as far as to
implement all three in version 7 (2003).

However, Netscape had its own DOM event model (*EventListener).
In 2000, it became the DOM Level 2 Events specification. Safari
1 (2003) implemented this model; Opera 7 (2003) also implemented
this model. As the ruins of Netscape became Mozilla, Firefox 1
(2004) inherited the model.

For the first section of the second decade (2000—2004), Microsoft
reigned supreme. Internet Explorer 6 (2001) was far and away the
best browser at the time. One of its competitors, Opera 6 (2001),
had yet to implement the DOM Level 1 Core (createElement et al.)
Microsoft implemented it in Internet Explorer 4 (1997) before the
specification even became a recommendation (1998).

However, the second section of the second decade (2004—2010)
would prove disastrous for Microsoft. In 2003, Apple released
Safari 1.0; in 2004, Mozilla completed Firefox 1.0. Microsoft
was seemingly asleep on its throne atop the browser mountain.
Internet Explorer 7 was not released until 2006: a gap of five
years dating back to Internet Explorer 6's release date.
Unlike Internet Explorer versions 4 through 6, version 7
innovated little; DOM changes were minute. Nearly two-and-a-half
years later, Internet Explorer 8 was released. Microsoft had awoken
from its slumber and noticed the coalescence other browser vendors
had formed around numerous web standards. Unfortunately, too much
time had passed since Microsoft's last real innovation. A movement
had been created amongst browser vendors. New DOM features were to
be added in specification form to the W3C; Microsoft's ideas were
left in the past. Microsoft's event model (*tachEvent) was
eschewed for the DOM Level 2 Events model. Internet Explorer did
not implement the preceding model until version 9 (2011), which
became the DOM Level 3 Events model.

Microsoft's (DOM) follies can be summed up by the following points:

presence as a core feature of Windows, and the resulting
OS-level security requirements;

reliance on ActiveX for client-side code;

innovation that tapered off curiously after version 6 (2001).

(Web) Developers

Secondly, developers bear a certain amount of blame. As the web
has continued to take off, more and more people are "dabbling"
in web development. This had led to a dilution in talent and
work ethic. The problem, however, lies mainly with attitude.
"Get it done quick" has taken precedence over "Get it done right."
As a result, innumerable web pages are incompatible with various
browsers. One of the leading causes of this incompatibility
is a practice called "user agent sniffing". Though the practice is
still in use today, it has been proved as both erroneous and harmful.
Opera even went so far as to "freeze" the user agent version at
"9.80" in version 10 (2009) and beyond. This was intended to
prevent erroneous scripts from breaking. A much better practice
called "feature testing" (albeit in mostly naïve form at the
moment) has been adopted by developers.

Ignorance

Thirdly, my preferred point of blame is ignorance; ignorance in
the fact that browser vendors did not work together nearly enough
to create unified specifications; ignorance in the fact that
Microsoft shunned users of other browsers; ignorance in the fact
that developers are either too lazy or too myopic to bother
researching browsers (especially those that are not en vogue.)
There are many differences in APIs and implementations. Most
can be avoided with a simplified-yet-defensive approach
(reliance on DOM 0) along with copious amounts of both research
and testing. Ignorance has led to the notion that Internet
Explorer 6 is a blight upon the Earth (recall its spot on the
browser throne mentioned earlier.)

Reflection

Sadly, the DOM is just a misunderstood API. Many desire to
throw stones (via FUD), but few desire to learn its intricacies.
One result of this ignorance is the introduction of DOM "selectors".
The DOM at heart is an API to manipulate document tree(s). Tree
traversal should be used for complex problems given the form of
a parsed document. With the introduction of the DOM Selectors API,
a developer can now leverage the CSS traversal engine of the
browser. This is quite convenient, but it conceals the true form
of a document tree. With "selectors", element node retrieval is
elementary. However, the DOM has eleven other node types specified.
What of text nodes? Comment nodes? Document nodes? These are also
nodes that are often desired while interacting with the DOM.

Conclusion

In short, take your time and read the various DOM specifications.
Test code in as many browsers as possible. If Internet Explorer
is perceived to be behaving oddly, consult MSDN. Most often,
the behavior is documented.

(Historical anecdotes can and may be inaccurate; any inaccuracies
are welcome to be raised.)

—Matt

Title: What's so bad about the DOM?


答:
I can tell you that there have been several places I've worked where they wouldn't even consider someone who didn't have their own projects outside of work. It exhibits love for programming beyond just showing up to a job and collecting a check. I'm going to go out on a limb here and say this: All programmers who don't love to program suck at their job. Even worse, they have nothing to add to any team they could join.

I'd take an inexperienced junior developer that loves what he does so much he plays with code in his free time over three mid-level developers that are just going through the motions: That junior developer will be great some day, and the others will never be any better than they are.

If you're not learning new things, you're just sitting around forgetting what you know.


问:
Trying to sort the coefficients of the polynomial (z-a)(z-b)(z-c)...(z-n) into a vector
So I have a factored polynomial of the form (z-a)(z-b)(z-c)...(z-n) for n an even positive integer.  Thus the coefficient of z^k for 0 <= k < n will be the sum of all distinct n-k element products taken from the set {a,b,...,n} multiplied by (-1)^k, I hope that makes sense, please ask if you need more clarification.

I'm trying to put these coefficients into a row vector with the first column containing the constant coefficient (which would be abc...n) and the last column containing the coefficient for z^n (which would be 1).

I imagine there is a way to brute force this with a ton of nested loops, but I'm hoping there is a more efficient way.  This is being done in Matlab (which I'm not that familiar with) and I know Matlab has a ton of algorithms and functions, so maybe its got something I can use.  Can anyone think of a way to do this?

Example: (z-1)(z-2)(z-3) = z^3 - (1 + 2 + 3)z^2 + (1*2 + 1*3 + 2*3)z - 1*2*3 = z^3 - 6z^2 + 11z - 6.  Note that this example is n=3 odd, but n=4 would have taken too long to do by hand.

Edit: Let me know if you think this would be better posted at TCS or Math Stack Exchange.

答:
if you have an array {a,b,c,...,n} then your starting result is {1}

you pop of the front (a) shift a copy of the subresult by 1 (add a 0 at the end) resulting in {1,0} and add the subresult with each element multiplies by a so the new subresult is {1,a}

do it again and you get {1,a,0}+{b*1,a*b}={1,a+b,a*b} again and you get {1,a+b,a*b,0}+{c,c*(a+b),c*a*b}={1,a+b+c,a*c+b*c+a*b,c*a*b} and so on...


问:
Build tools for php, html, css, js web app development
What are some recommendations for a build tool that would allow me to upload changes to a web server or a repository and minify the js and css automatically, and possibly even run Closure compiler on the JavaScript?

I'm not worried about doing anything with the php code other than update with most recent changes although in the future would like to have phpdoc updated automatically.

Just wondering if there is some way to do all this other than an amalgam of scripts that run or have to be invoked every time?

答:
The way I read this it sounds like you looking for a Continuous Integration server.  You could leverage something like Hudson or phpUnderControl allowing you the flexibility to use almost any pre-build and deployment tools you want.   And builds can be scheduled or run as required.

A quick Google search should get you started.

OR

If all the flexibility, automation and the bells and whistles are not required you could consider using Phing.  This article is a good place to start.


答:
I only see advantages on doing the UI first:

Get your customers involved in the design of the application earlier rather than later

Have a better idea of what the application must cover (which just adds to an existing requirements document)

Stake-holders can see better what they are paying for so they can take a more educated decision

Make changes early based on discussions about the UI

Get the chance to build a prototype (or proof-of-concept) if people are not fully confident on the solution yet

Are able to split your team to work on the UI while others work on other layers

More likely that your application will be user friendly (as you pointed yourself)

Gives you a much better reference in order to discuss features with your peers and your client

Allow you to better decide on what will be implemented so later if your client comes back complaining some feature is missing you can point back to the mockups and prove them wrong

You don't even have to use Photoshop or anything fancy (or expensive) to design your UI first. You could use this very nice (and non-expensive) tool called Balsamiq. It allows you to build very clean mockups that allows you to focus on functionality rather than fancy stuff which is very important at an early stage.

I've been through pretty much every scenario that I just listed and designing the UI first has been a very good decision for me in several projects.

The only drawback I'd say is that it takes more time upfront. But that's not even a valid argument against it since you'll definitely save more time later based on everything I just listed.


答:
Compared to almost any other field I can think of, programming is basically all about self-education. Formal computer science/software engineering education is useful, but it's not really where you learn to code.

What you should really do is just start working on projects: build something that you want to exist. And then join an open source project to work on something that you want to be even better. The learning comes for free then...