问:
What should be in my model and what should be in my controler?
We are writing a system with a sort of quasi-MVC structure (it was never stated as that, but that's what it is).  I'm building up a full knowledge of the system and the controller will have to make calls to me to update it; they system itself is something similar to a graph.

We need to have a sense of a path between multiple nodes, and a way to identify the original node.  I receive connections between two nodes in my original graph building, so knowledge of the full path, and the origin node, is not read in directly but obviously can be inferred once I finish building the graph.

My instinct was to write a basic path tracing sort of logic into my model. Every new edge we would infer the path's that exist and any original input nodes by tracing the path forward and backwards as appropriate.  Tracing the path forward or backward does require a bit more knowledge of a system the connection between edges and nodes are a little more complicated then just edge 1 connect node A to B.

My question is, would doing this still be within the realm of the model?  If I do all this path tracing, determining input nodes, identifying paths etc am I doing too much work which I should really be storing in the controller for easier modification later?  I need to have some tracing capability to build the original graph before the controller is even initialized, but of course I could have the controller provide methods I call to do path tracing and the like an use the controller implementation when building the graph.  I don't think the logic for the graph itself will change, only the way we use it for tasking, and doing things in the model makes it easier because the model can modify it's quasi-immutable objects directly while I'm not allowing the controller to do that without calls to the model (package scope variables).

答:
Try to fit as much in the model as you can. Controllers are just for business actions, which are usually just variations of CRUD (create, read, update, delete). Models are for doing the advanced logic. For example, business requires that I view the path from A to B. The controller action for viewing a path would tell the model to find and trace the path for it. Then the controller would pass the data back to the view. Controllers mostly just pass data back and forth.

Here's a good analogy: http://nuts-and-bolts-of-cakephp.com/2009/01/06/another-way-to-think-about-mvc/. It's for CakePHP, but it should be true for all MVC.


问:
A design pattern for data binding an object (with subclasses) to asp.net user control
I have an abstract class called Address and I am  deriving three classes ; HomeAddress, Work Address, NextOfKin address.

My idea is to bind this to a usercontrol and based on the type of Address it should bind properly to the ASP.NET user control.

My idea is the user control doesn't know which address it is going to present and based on the type it will parse accordingly.

How can I design such a setup, based on the fact that, the user control can take any type of address and bind accordingly.

I know of one method like :- Declare class objects for all the three types (Home,Work,NextOfKin). Declare an enum to hold these types and based on the type of this enum passed to user control, instantiate the appropriate object based on setter injection.

As a part of my generic design, I just created a class structure like this :-

I know I am missing a lot of pieces in design. Can anybody give me an idea of how to approach this in proper way.

答:
Looks like a candidate for a Strategy Pattern to me. In a simplistic approach, use delegates to perform the binding based upon type.

It is just as you demonstrate in your diagram whereby the point of the strategy pattern is to encapsulate behavior, ensure class not doing more than one thing, and to use Delegate Pattern to designate a specific interface and concretes to perform a specific function.

ContentLicense: CC BY-SA 3.0


问:
Do you find languages with indentation requirements cumbersome?
Thoughts on these?  Python is one example, and no this is not a stab against Python I like the language.

What languages have a indentation requirement?

答: No. I rarely get bitten by indentation requirements (perhaps because I'm a stickler for detail). I'd indent my code anyway, so it's not a problem. (The only time it's been an issue is with some old Python code I'm working on; the previous developers wrote it with 2-space tabs (ick!), then newer developers created some files with 4-space tabs, and I have my editor set to 4-space tabs, so indentation is kind of a pain in the older files.) I've never had a problem with it in Haskell, either. It's a bit annoying in Makefiles, but I wouldn't say it's "cumbersome".</p>

ContentLicense: CC BY-SA 2.5


问:
VB.NET: Two tiers for three layers or three tiers for three layers
I asked a question on StackOverflow in November about separating a very large application into layers and tiers: https://stackoverflow.com/questions/13342626/net-divorcing-layers.  The previous developer included data logic and business logic in the business logic layer

My question is about the tiers element.  I researched on here and concluded that it is better to separate layers into tiers contained in separate DLLs i.e. the presentation layer, business logic layer and data access layer all have separate DLLs as described here: https://stackoverflow.com/questions/13342626/net-divorcing-layers.  This seems to be consistent with what I lEarnt at university.

However, since then all the examples I am finding online suggest having two tiers (One for the presentation layer and one tier for the BLL and DAL).

Is there any specific criteria that developers use to decide whether or not to use three tiers?

I am using ADO.NET and have a shared SQL Helper class in the data access layer.  The SQLHelper class is similar to this but for VB.NET: http://www.sharpdeveloper.net/source/SqlHelper-Source-Code-cs.html

答:
Is there any specific criteria that developers use to decide whether or not to use three tiers?

Whether or not the software layer must be capable of running on a separate machine.  That's the difference between a tier and a layer; a tier is a hardware abstraction.

While the concepts of layer and tier are often used interchangeably, one fairly common point of view is that there is indeed a difference. This view holds that a layer is a logical structuring mechanism for the elements that make up the software solution, while a tier is a physical structuring mechanism for the system infrastructure.

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


问:
Possible to Comment on a storyboard?
I recently started working for a company that has me making mockups for an app they'd like to see converted to an iPhone app. I have not been informed as to how all the boards fit together, but I do have a general idea on what they should look like. I would like to write notes or comments on each individual board about how things should be done once I have more information. Is it possible to comment on a board or is there some place close to the boards where I can leave notes on what to do next? </p>

答: Interface builder (and, as an extension, Xcode + Storyboards) has a built-in 'notes' section for any object in the hierarchy, which may be exactly what you need:

Title: Possible to Comment on a storyboard?


问:
Differences between TypeScript and Dart
Microsoft recently unveiled Typescript, a new JavaScript-like programming language.
Some time ago, I heard about Dart, a new programming language created by Google to solve problems related to Javascript like performance, scalability, etc..

The purpose of both new languages seem the same to me.. What do you think?

Are the purposes of the languages the same?

What are the real differences about them?

答:
While the question was "Are the purposes of the languages the same?", the real question is: "How can we make web programming better from where we are?".

Both projects try to do this considering

programming language (TypeScript makes a small but very clean step, Dart makes the more revolutionary move that is still moving)

interoperability with existing js code (0 transition in TypeScript which compiles to js, complicated in Dart, since 2 VMs talk to each other)

software engineering practices (Dart only, web components and shadow dom)

Over the last 3 days I dived deep into Dart and then into TypeScript. My CoffeeScript codebase went to 2000s lines of code, too much to be handled with lovely but too fluffy CoffeeScript. The problems I faced was that CoffeeScript lacks features that languages designed for medium to large scale programming have: interfaces, modules, type safety. But there was one even much more serious issue with coffee and js: The js "this pointer" weirdness affected my sanity and CoffeeScript does not help anything here.

So here my results after 3 days of eval and usage:

Dart

Went thoroughly through the tutorial, reading 1 book, skimming 2nd book and tried the demos. I thought, Dart that is the future. Then I tried to migrate my app to Dart. That was were my enthusiasm went down from 100 to 10. Here is why:

The Dart Editor is the only way to program Dart. While plugins for Sublime Text exist, they do not provide features like intellisense, code completion (correct me if I am wrong). The Dart Editor is however in pre alpha quality. While it does support supercool magic things like updating the web page when you edit the CSS file (! really cool) it hangs or crashes several times a minute. So you type 5 letters and 2 times you have to wait 2 seconds or 15 seconds between typing. And I had a project with some lines of code, so did not want to wait what happens when 1000s lines are in. Moved a file from one folder to the other inside Dart Editor, crash. Debugging with the Dart Editor is at first sight better than all js debugging tools I know (chrome is my choice), but there are still too many things missing: No immediate window (this makes js debugging much better at the moment), no watches.

Politics and Escape Possibilities: Some say that Apple, MS and Firefox will never ever provide Dart VMs. Well, I am not so sure, but at least for Apple this appears at the moment very certain. For the others its more likely than the opposite. So no problem, we can convert Dart to JavaScript. The way this integration works is  really great, Dart maintains a js stub that keeps the js code connected to the Dart Editor, so a print() statement still appears in Dart Editor, cool. But here comes the but: the footprint of such converted code is high. 150kB or so (before minification). I did not dig too much into the exact size, so do not nail me down on this.

Language Maturity. Beside the way too serious issues with Dart Editor popping into my face 3 times a minute I also found it unacceptable that every source about Dart code you find uses a different Dart. The language changes every day. You find a post from 5 weeks ago? It is outdated. You try the samples from the Google tutorial? At least 1 sample does not compile since an API changed. Even mundane things, like attaching an event to a DOM element are in good move.

Integration with existing js libraries is a bit involved. 2 VMs need to communicate here, its tricky.

As a conclusion, you cannot seriously use Dart as of today, and diving into it is not too much fun due to 1 and 3. Both points will disappaer over time. About the 2 point, Google published performance benchmarks some days ago demonstrating that their compiled js is better than handwritten js. My compliments, great job. Loading time might still be behind due to the footprint issue as said. However, if the footprint code gets used by many many sites, it might be available cached and voila, disappears as well.

So: I consider Dart a great project, using it at the moment carries a good portion of unforeseeable risk and it will take this year to get it to good stable level.

TypeScript

Evaluating TypeScript is very easy, takes 1 or 2 hours and you know everything. Reading the language spec document and a short book (TypeScript revealed) revealed, I knew everything and started programming. I was then surprised to find that TypeScript's additions to JavaScript just fill every serious need I had to enhance my client programming. Here the highlights:

Interfaces. Encapsulation and interfaces allow me to structure my code easily. Perfect!

Class State.. TypeScript allows to express the state that instances of a class carry explicitly, or better it enforces it. This is a large step better compared to js or coffee.

this call craziness mitigated. Inside arrow functions, TypeScript makes the this pointer like any normally behaving citizen.

Editor, Intellisense. TypeScript comes with 100% top perfect intellisense that reacts in the micro or millisecond range as used from Visual Studio when programming C#. TypeScript headers for all important js libraries exist too. Great great great.

Experience and Risk. Using TypeScript carries zero risk, the language is clearly defined, perfectly stable, it is just js with sugar, nothing unforeseeable.

Actually, these enhancements give me everything I needed. The only thing I would like to see in the future are generic collections. But that is peanuts.

So what about performance? While I consider myself a performance freak, I do not believe that there is any project that would make the technology choice here based on performance. Both are in the js liga.

If you are interested in the future of web programming, both are great efforts, TypeScript is much more pragmatic and usable now, Dart is a very interesting lab project that will be usable once mature editors and debuggers are available and the scope of projects doable with it will depend on politics.

In any case the 3 eval days were mostly fun and I learned a lot, if you find the time, it takes 1 day for Dart and 2 hours for TypeScript to make your own opinion. Try it.

Update October 2014

It has been a while and ex post it appears the assumption that Typescript is the safe stable route to go was quite right. I just found a (very) prominent statement about Typescript, Dart and Closure:

I have been interested in the challenge of Web programming in the large for quite some time. I believe that Google Closure is currently still the best option for large-scale JavaScript/Web development, but that it will ultimately be replaced by something that is less verbose. Although Dart shows considerable promise, I am still dismayed by the size of the JavaScript that it generates. By comparision, if TypeScript can be directly translated to JavaScript that can be compiled using the advanced mode of the Closure Compiler, then we can have all the benefits of optimized JavaScript from Closure without the verbosity. What's more, because TypeScript is a superset of JavaScript, I believe that its syntax extensions have a chance of making it into the ECMAScript standard at some point, whereas the chances of Dart being supported natively in all major browsers is pretty low.

http://blog.bolinfest.com/2013/01/generating-google-closure-javascript.html

Michael Bolin is a long time (ex)google (ex)fb front end hero, also involved in google closure (get his book about Closure).

Google Traceur

Google's appraoch to live ECMA Script 6 today is its Traceur project:
https://github.com/google/traceur-compiler

Compared to Typescript, tooling support is presumably far behind as of today. On the upside however, it is much faster in adopting overly cool future js language ehancements like iterators or comprehensions.

Facebook Flow, Google AtScript

provide similar features as TypeScript.

"One may wonder what’s with these different JavaScript type checking solutions and what to do about it. A good news is that Microsoft, Facebook and Google are collaborating on these, according to Microsoft’s Jonathan Turner:

The TypeScript team is working with both the Flow and AtScript teams to help ensure that resources that have already been created by the JavaScript typing community can be used across these tools.  There's a lot these projects can learn from each other, and we're looking forward to working together going forward and creating the best tools we can for the JavaScript community.  In the long term, we will also be working to fold the best features of these tools into ECMAScript, the standard behind JavaScript."

infoq article on fb flow

Title: Differences between TypeScript and Dart


答:
In general, you shouldn't. The user control should bind to a concrete type.

A better approach would be to have the base address bits be their own class, and then compose 3 classes for the optional bits, each containing a base address class as a member. The user control can then defer the rendering of the address bits to some sub-control.

Or better yet, simply include the home/work phones and next of kin (and leave them blank if unused). It's not as though those elements are mutually exclusive (or should be anyways...).

Title: A design pattern for data binding an object (with subclasses) to asp.net user control

Body:
I have an abstract class called Address and I am  deriving three classes ; HomeAddress, Work Address, NextOfKin address.

My idea is to bind this to a usercontrol and based on the type of Address it should bind properly to the ASP.NET user control.

My idea is the user control doesn't know which address it is going to present and based on the type it will parse accordingly.

How can I design such a setup, based on the fact that, the user control can take any type of address and bind accordingly.

I know of one method like :- Declare class objects for all the three types (Home,Work,NextOfKin). Declare an enum to hold these types and based on the type of this enum passed to user control, instantiate the appropriate object based on setter injection.

As a part of my generic design, I just created a class structure like this :-

I know I am missing a lot of pieces in design. Can anybody give me an idea of how to approach this in proper way.


问:
How safe & trustworthy are hosting sites such as sourceforge, github or bitbucket for closed-source projects?
I am considering using sourceforge, bitbucket or github for managing source control for my business.  I have open projects and I participate in open projects such as gcc.  But I also have a business where I develop closed-source software for my living.

How trustworthy are sourceforge, github or bitbucket in terms of keeping software secure from prying eyes?  How stable is the hosting in terms of data loss prevention?  Has anyone out there based their business logic with such an outfit?  Has anyone out there surveyed several of the hosting solutions?

答:
There's no good, standard, way to evaluate the security of providers like this. Stability you can see, somewhat, but security is pretty much impossible to evaluate from the outside.

I'd actually talk to the providers you are considering about their security guarantees, and look at their contracts - if they don't make any guarantees, or if their contracts are riddled with 'we can not be held responsible' clauses, then that tells you how seriously they take security, and how much help you can expect if something goes pear shaped.

Also, don't evaluate this in a vacuum - think about what it would take for you to run your OWN servers, and how much effort and overhead that would take, and how likely you are to screw it up (leaving a massive security hole) by doing it in house.


问:
Is it possible to integrate MS Project Server with SVN
We have been using Hosted SVN + Fogbugz for our source control and task/issue tracking. Our developers are very comfortable with SVN and we are hesitant to switch source control (e.g. TFS) providers at this point. However, Management extensively uses Microsoft Project for project management and are considering setting up MS Project Server.

EDIT With SVN + Fogbugz (or several other task tracking tools), we can create a post-commit hook to update tasks (close/reopen/specify time) from commit messages.

Does anyone know of a way to intergrate MS Project Server with SVN? Is it even possible?

I searched online but could not find anything. Maybe I did not search correctly?

答:
You've got a few related questions here:

Does anyone know of a way to intergrate MS Project Server with SVN? Is it even possible?

As the comments to the questions indicate, yes this is definitely possible, I'm more familiar with the Project Server Interface (PSI = the MS Project Server API) and less with commit hooks on the SVN side. Updating tasks through the PSI with completed percent or finished date is pretty straight forward. But yes, it's writing .NET managed code.

I don't know of any existing "shrink-wrapped" options. I can't imagine how one would work without moderate customization specific to the Project Server instance: do you track percent complete or hours effort, how to you map bugs/changes to tasks, &c &c.

And most shops heavily invested in MS Project Server will be working with more MS stack, such as TFS work item tracking, which does have Project Server integration out of the box.

So I doubt the pre-built solution you are looking for exists. Also,


答:
A few good answers already covering the technical aspects of what you are concerned about - I won't reiterate those. Ultimately, in the event of a "security breach" you need to consider the legal recourse you have. What are the terms of the license, to what extent are they responsible for damages you suffer as a result for service failure etc. For your specific case, can the damages be recovered in cash. You also need to consider how secure your alternate is. Is an in-house server, presumable connected to the internet, any less likely to be compromised than Github? Are you skilled enough and putting the require resources into your installation to be certain?

I am working with an organization looking at putting data in the cloud - however, there data , although having limited commercial in value, is legally sensitive. No amount of cash damages would fix a security breach. As a result, their measure of secure is "more secure than running in-house systems". This is followed with legal jurisdiction - the provided must answer to the same legal system - in our case, same country, as they would fall under same laws regarding data security, privacy etc, and a breach is likely to be answerable in criminal, not just civil courts. Cross border legal disputes are to be avoided at all costs, as are cross border criminal complains.

Title: How safe & trustworthy are hosting sites such as sourceforge, github or bitbucket for closed-source projects?

Body:
I am considering using sourceforge, bitbucket or github for managing source control for my business.  I have open projects and I participate in open projects such as gcc.  But I also have a business where I develop closed-source software for my living.

How trustworthy are sourceforge, github or bitbucket in terms of keeping software secure from prying eyes?  How stable is the hosting in terms of data loss prevention?  Has anyone out there based their business logic with such an outfit?  Has anyone out there surveyed several of the hosting solutions?


问:
Using a development language (Python) before putting it into C++
I'm kinda having a debate here with my friend, whether it's OK to have a development language before putting the idea into C++.

When I say development language I mean a language to try ideas out before putting them into the compiled language, in this case C++.

My friend thinks it's unnecessary (and maybe a waste of time) to do this because we basically have to re-write code, or in other words, port the code from the dev language to C++ code.

I think otherwise though, it saves a lot more time to be porting the code than to wait for the C++ code to be compiled over and over while we test little things out.

FYI, we're talking about code for a small application, the idea is for the entire application (actually a game), once done weighs less than 100MB, however I'm aware the size already compiled is much MUCH smaller than in code.

Of course, this can also go the other way around, should we only use the compiled language (C++) or should we only use the scripting language (Python).

Thanks for your help!

答: This is perfectly ok, its called prototyping, also software prototyping. Wether or not it suits your particular application is something you need to decide on your own. For example, testing a GUI design migth be something worth mocking up quickly, just to see and feel how it'd work.</p>


问:
Best practices for sharing tiny snippets of code across projects
I always try to follow the DRY principle strictly at work; every time I've repeated code out of laziness it bites back later when I need to maintain that code in two places.

But often I write small methods (maybe 10 - 15 lines of code) that need to be reused across two projects that can't reference each other. The method might be something to do with networking / strings / MVVM etc. and is a generally useful method not specific to the project it originally sits in.

The standard way to reuse this code would be to create an independent project for the reusable code and reference that project when you need it. The problem with this is we end up in one of two less-than-ideal scenarios:

We end up with tens/hundreds of tiny projects - each to house the little classes/methods which we needed to reuse. Is it worth creating a whole new .DLL just for a tiny bit of code?

We end up with a single project holding a growing collection of unrelated methods and classes. This approach is what a company I used to work for did; they had a project named base.common which had folders for things like I mentioned above: networking, string manipulation, MVVM etc. It was incredibly handy, but referencing it needlessly dragged with it all the irrelevant code you didn't need.

So my question is:

How does a software team best go about reusing small bits of code between projects?

I'm interested particularly if anyone has worked at a company that has policies in this area, or that has come across this dilemma personally as I have.

note: My use of the words "Project", "Solution" and "Reference" come from a background in .NET development in Visual Studio. But I'm sure this issue is language and platform independent.

答:
My company uses intranet-local web services. We have a few web services that are set up as common internal web services, and when another project needs access to one of the services it sends an http request with a defined interface. Since it's on the intranet, housed in the same server farm, these requests are very fast.

Obviously this only works with internet apps (and only works in millisecond times when on the same local network), but it has some really nice advantages.


问:
Performance overhead of standard containers and boost
Adap.TV has chosen C++ to develop their software. However, they've decided not to use the standard containers1 and boost for performance reasons, as they've blogged about it in the following article:

Why we use C++ (without using STL or boost)

It says (emphasis mine),

There are several rules that we are obeying in order to keep the performance high;

  Avoid malloc(), calloc() or new

  No free() or delete (and no need for tcmalloc)

  No STL, boost etc.

  Avoid locking as much as possible

  # threads = # CPU cores (hyperthread is a trade-off between latency and throughput)

As we know, the standard containers use allocators which uses new and delete internally which are expensive operations. So to avoid them, AdapTv has avoided using standard containers altogether. Instead of using new and delete (repeatedly), they reuse memory (which implies they use a memory pool).

I'm wondering what's stopping them from using custom allocators for the standard containers! The custom allocator could use a memory pool internally which means memory reuse. So I don't see how standard containers would hurt performance.

Or am I missing something? Can't we avoid using new and delete with standard containers? Is there any other reason why would anyone avoid using standard containers? Or is it simply a lack of knowledge on their part which led to this decision?

And how about boost?

1) I suppose by STL they meant C++ standard containers, not SGI's STL.

答:
Obviously malloc() and free() reuse memory, from the "pool" of your available RAM plus swap.  However, in the interest of making efficient use of resources, they make a number of trade offs for general purpose computing.  The glibc source and this article they reference discuss the trade offs in pretty good detail.

The most prominent trade off is time-space.  Essentially, if you want your allocator to be faster, you are going to end up wasting some space.  Pre-allocating a memory pool is an example of wasting space, since you have to allocate as much memory as you think you will ever need.  In a single-purpose computer like a server, that trade off is acceptable.  You're not going to want that memory for another application.

If you use STL custom allocators, you get control over where the memory comes from, but you still can't control when and how often the allocator is called.  Every once in a while, you unavoidably take a big hit, like needing to defragment.  You also usually need locking.  They are avoiding that problem altogether, at the expense of wasting some memory.  Wasting is probably the wrong word though, since it's a deliberate choice.  You're investing the memory to gain speed.

As a side note, it also happens to increase reliability.  I used to work somewhere with a prohibition on dynamically allocated memory, but not for performance reasons.  If all your memory is allocated at the beginning, you can easily determine your maximum memory requirements, and know a burst won't put you over your physical limit.


答:
For small bits of code -- say a single class with no dependencies -- we tend to just copy and paste the code into projects. This sounds like a violation of DRY, and I'll admit it can be at times. But over the long term it has been much better than having some sort of massive, multi-headed commons project for a few reasons.

First, it is just simpler to have the code handy, especially when building and debugging stuff.

Second, invariably you'll want to make some little tweak to the common code for that project. If you've got a local copy of the source than you can just make the tweak and call it a day. If there is a shared library then you could be taking on tweaking that library and then making sure you don't break all the other apps or creating a versioning nightmare.

So if it isn't beefy enough for it's own namespace we tend to just push it into the appropriate bits on the project and call it a day.

Title: Best practices for sharing tiny snippets of code across projects

Body:
I always try to follow the DRY principle strictly at work; every time I've repeated code out of laziness it bites back later when I need to maintain that code in two places.

But often I write small methods (maybe 10 - 15 lines of code) that need to be reused across two projects that can't reference each other. The method might be something to do with networking / strings / MVVM etc. and is a generally useful method not specific to the project it originally sits in.

The standard way to reuse this code would be to create an independent project for the reusable code and reference that project when you need it. The problem with this is we end up in one of two less-than-ideal scenarios:

We end up with tens/hundreds of tiny projects - each to house the little classes/methods which we needed to reuse. Is it worth creating a whole new .DLL just for a tiny bit of code?

We end up with a single project holding a growing collection of unrelated methods and classes. This approach is what a company I used to work for did; they had a project named base.common which had folders for things like I mentioned above: networking, string manipulation, MVVM etc. It was incredibly handy, but referencing it needlessly dragged with it all the irrelevant code you didn't need.

So my question is:

How does a software team best go about reusing small bits of code between projects?

I'm interested particularly if anyone has worked at a company that has policies in this area, or that has come across this dilemma personally as I have.

note: My use of the words "Project", "Solution" and "Reference" come from a background in .NET development in Visual Studio. But I'm sure this issue is language and platform independent.


答: Old-fashioned FORTRAN and COBOL had indentation requirements based on punch-card layout, which I found annoying.  Indentation requirements don't seem to bother me provided I can use all columns, but having to be careful to start a line on column 7 because 6 is for line continuation is awkward.</p>

Title: Do you find languages with indentation requirements cumbersome?

Body:
Thoughts on these?  Python is one example, and no this is not a stab against Python I like the language.

What languages have a indentation requirement?


答:
Your model contains information that your view needs to display. This includes:

Data bound fields

Various results

Generated text

In your context, consider the model to be populated with data that is needed to be displayed from within the view.

With regards to the controller, an action in a controller does the following:

Perform any entry validation

Perform any business logic

Populate the model

Return the view, populated with the model.

The exception to the above is for languages that support annotations where you can have your validation on model fields.

My question is, would doing this still be within the realm of the model?

Potentially. It's likely to be a poll type answer, but in my opinion it is acceptable to have methods within a model that transforms data already present within the model. It should be purely transformative, and not have any external consequences.

Title: What should be in my model and what should be in my controler?

Body:
We are writing a system with a sort of quasi-MVC structure (it was never stated as that, but that's what it is).  I'm building up a full knowledge of the system and the controller will have to make calls to me to update it; they system itself is something similar to a graph.

We need to have a sense of a path between multiple nodes, and a way to identify the original node.  I receive connections between two nodes in my original graph building, so knowledge of the full path, and the origin node, is not read in directly but obviously can be inferred once I finish building the graph.

My instinct was to write a basic path tracing sort of logic into my model. Every new edge we would infer the path's that exist and any original input nodes by tracing the path forward and backwards as appropriate.  Tracing the path forward or backward does require a bit more knowledge of a system the connection between edges and nodes are a little more complicated then just edge 1 connect node A to B.

My question is, would doing this still be within the realm of the model?  If I do all this path tracing, determining input nodes, identifying paths etc am I doing too much work which I should really be storing in the controller for easier modification later?  I need to have some tracing capability to build the original graph before the controller is even initialized, but of course I could have the controller provide methods I call to do path tracing and the like an use the controller implementation when building the graph.  I don't think the logic for the graph itself will change, only the way we use it for tasking, and doing things in the model makes it easier because the model can modify it's quasi-immutable objects directly while I'm not allowing the controller to do that without calls to the model (package scope variables).


问:
Time required to start coding at a new company
I am a software engineer for 4 years, and I just changed my company for the first time.

Company works with pair programming, and it's been 3 days, I couldn't even write a single line of code.
It's so frustrating for me because I was very productive at my previous company.

The codebase is large, they are using 5-6 languages/tools that I am not familiar with, like rspec, haml, jasmine and others. But still, I feel awful.

This weekend I created UML to get better understanding of the application, but still I am guessing I'll not be able to write decent amount of code this week.

Is this normal?

What is your experience when you change your job, and dive into a large codebase written with languages/libraries you are not familiar with.

Of course I am not asking for exact time required, but past experiences or things to make the process would be great.

Btw, I've already read below questions&answers,
How do you dive into large code bases?

https://stackoverflow.com/questions/215076/whats-the-best-way-to-become-familiar-with-a-large-codebase

https://stackoverflow.com/questions/214605/the-best-way-to-familiarize-yourself-with-an-inherited-codebase

UPDATE

All great suggestions! I just came from work, I've worked a lot!

About pair programming:

Generally they write code, and I am trying to not miss even a second!
If I try to write the code, I know it's gonna take forever, because I don't even know which files should I edit, but beside that, as I said, they are using 6-7 languages/frameworks that I'm not familiar with, and learning all these syntaxes at one is not easy.

How well the company prepared for engineers:

I can't say they are well organized, they kind of expecting me to start writing code immediately.

Taking notes, being proactive:

I'm always taking notes when they write a new command/or anything about data models.
My peers are very smart and kind people, and I'm trying to ask lots of questions, even lots of stupid questions sometimes.

Is this common?:

@Telastyn, thanks for your answers, it made me feel a little better. It seems like my problem is not that uncommon, but I was really productive before this job, and now I really feel useless and not smart.

I hope I can start solving bugs/implementing issues very soon.

About frameworks/languages they use:

I was really honest about that, I didn't say I know something that I don't know actually.
But I wasn't expecting that much different things, and since I started working at the day I accepted the offer, I didn't have time to prepare myself.

@Southpaw Hare, thanks alot for sharing your experience. You are absolutely right. There is no guarantee that I'm going to learn all of these stuff, but I'm trying.
At the end, it's is hard to learn all of the syntax at once, and I think that is the main problem too. Because I can navigate in ruby code well since I know that language, and I navigate in js codes thanks to browser inspectors, but the problem is writing the actual codes with the frameworks/languages I don't know.

答:
It really depends on the job you are doing and the role that you're in.

If you're doing contract-based work, you're expected to literally hit the ground running, using all the skills at your disposal to get the work done. Contract work is generally well defined and you're (usually) able to do this, at least in my experience.

On the other hand, I've started at one place that had an enormous legacy code base with a huge learning curve. We weren't expected to be writing production code for the first six months we were there.

Be patient, absorb as much as you can and put it to good practical use when you do get to start coding. If you're inpatient or rush there is a good chance in such a large system you might end up breaking something, particularly if their test coverage isn't brilliant.


问:
Criteria for selecting MigLayout for GUI code?
It seems to be easier to use and more feature rich than standard swing layouts. It looks like a do it all replacement for all standard layouts. If you are making simple code to just show the time in a window, then MigLayout is probably not useful. But, if you are making a flight cockpit panel, then MigLayout might be the best. However, even if your project is "complex" (like the flight panel example), how do you decide if you can do it well with the standard layouts instead of Mig ?

How do you know when you should use MigLayout and when you should not ? Is it so good that one should use it right away for big projects without even considering the standard layouts ?

These are the kind of points I am looking for -

(1) (fictional) - Mig can be slow for "big projects". If you want a fast loading GUI, then use the standard layout.

(2) (fictional) - Mig is still not as mature a project as the standard layouts. If you are making a mission critical app, i'd suggest not using Mig.

答:
Swing developers should know the basic layouts and master at least one powerful layout. MigLayout is one such tool. The problem then becomes, "When should I use a powerful layout?" The answer is "When no simpler one will do."

Use simple layouts when possible.

Nest simple layouts for more complex effects.

Isolate complex layouts, such as GroupLayout and MigLayout.

Avoid the temptation to make a single layout manage the entire GUI.

Don't let a GUI designer dictate your GUI design.

OwnerDisplayName: david blaine


问:
How to reduce the number of bugs when coding?
No one's perfect, and no matter what we do, we are going to produce code that has bugs in it from time to time. What are some methods/techniques for reducing the number of bugs you produce, both when writing new software and changing/maintaining existing code?</p>

答: Use code inspection tools like ReSharper or IDEs like IntelliJ IDEA that warn about many copy-and-paste bugs and others by e.g. pointing out variables that "are written to, but never read". Has saved me a lot of time.


问:
How can I access my Handler/runnable class from all my other classes in Android?
I am trying to create a class which allows me to do something every 5 seconds and I want to be able to start and stop this from running from any of the other classes. Here is my Timer class:

```<code>public class Timer extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

}

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        public void run() {

            Toast.makeText(getApplicationContext(), "DISPLAY MESSAGE", Toast.LENGTH_SHORT).show();
            handler.postDelayed(runnable, 5000);
        }
    };
}
</code>```

Now my knowledge on Object Orientated programming is not as good as I thought it was, I am used to creating instances of classes and using the classes properties, but how can I use a classes properties once across the whole program, do I still create instances of the Timer class in other classes? Should I use the Singleton pattern, or should I make the class static?

So basically In Class1 I would like to start the timer by doing this:

```<code>Timer.runnable.run();
</code>```

And perhaps in Class2 stop the runnable started in Class1 by doing this:

```<code>Timer.handler.removeCallbacks(runnable);
</code>```

I am looking for advice and an explanation on the correct way to program this idea and why.

Thank you!

答:
You can use a application class http://developer.android.com/reference/android/app/Application.html

http://mobisoftinfotech.com/android-application-class-example-a-brief-tutorial-on-android-application-class/


问:
How do you dive into large code bases?
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?

答:
I once had a pretty fantastic software engineer tell me that the most expensive form of code analysis and maintenance was to walk through the code, line by line; of course, we're programmers, and that pretty much comes with the job.  The happy medium, I think, is to (in this order):
1.  Get a notebook to create notes for how you understand the code to work, and add to it as time goes on
2.  Refer to documentation about the code
3.  Talk to authors or others who have supported the code base.  Ask them for a "brain dump"
4.  If you're to the point where you understand some of the detail-level class relationships, do some step-through debugging of the code to do some synthesis between how you thought the code works and how the code actually works.</p>

Title: How do you dive into large code bases?


问:
How to deal with warnings in a legacy project
I work on a C++ project that generates bajillions of warnings. Most of the warnings appeared after the code was written:

Initially the project used Visual C++ 8, soon switching to 9, but there is little difference in the generated warnings. Warnings were either fixed or silenced, so there were no warnings then.

Then a 64-bit target was added. It generated a huge amount of warnings, mainly because of sloppy use of types (e.g. unsigned vs. size_t). No one bothered, or had time, to fix them once the code worked for the purpose.

Then support for other platforms using GCC (4.5 and 4.6, some 4.4 initially) was added. GCC is much more picky, so it generated many more warnings. Again nobody bothered, or had time, to fix them. This was complicated by the fact that GCC didn't have a pragma to silence a warning in particular bit of code until 4.5, and according to the documentation it is still not what one would need.

In the mean time some deprecated warnings popped up.

So now we have a project generating thousands of warnings. And I can't even say from how many places, since even .cpp files are compiled several times by different compilers and warnings in headers get printed over and over.

Is there a best practice for cleaning up something like that? Or at least some positive experience dealing with it?

答:
Either set aside a sprint/cycle to do preventative maintenance on the system, clearing out dead code, eliminating warnings, cleaning up bad comments, things like that, OR institute a policy to eliminate warnings as sources are touched anyway for something else.

I'd not do the former myself just to get rid of warnings, but if such a cycle were planned that'd be part of the workload. Reason for that is that touching a file for anything introduces risk of bugs, and thus risks the stability of your product.


答:
There's a similar question (with an answer written by me) on Stack Overflow:

How safe is it to host sensitive data on repository sites like github, bitbucket, etc.?

TL;DR:

as with everything in the cloud, there's no 100% guarantee that some hacker won't access your data

(on the other hand, that can also happen when you host your stuff yourself)

cloud providers may go out of service anytime. It's unlikely that this will happen to the big source code hosters mentioned, but you never know

--> it's your responsibility to take backups of your stuff regularly!


问:
Reuse MVC4 codebase / deploy MVC4 as standalone desktop application?
We have an MVC4 application that we would also need to distribute as a standalone (no network connectivity) desktop application. Rather than rebuild the HTML/JS front-end we would like to reuse that so in essence we're distributing a self-hosted HTML-view-based .NET MVC application. What we roughly envision is: MVC4 .NET DLL + JS libraries + Self-hosted HTTP core + self/embedded browser view. For this standalone desktop app, we're only concerned with Windows OS.

Question: Is that practically doable or just a theoretical idea? How would we practically go about achieving that? We are attempting to minimize codebase fragmentation (and duplicate maintenance). We anyways have to support IE for the "online" version of the MVC app.

To Clarify: The user experience we would like to have is:

Single large .exe file that encapsulates all resources within it

Double clicking it launches a rectangle window within which the HTML app is rendered. This would be similar to how iOS apps have an "HTML view" which uses the OS's in-built HTML renderer (on Windows I assume it's IE?)

答:
In theory, you absolutely can do this.

The second half of that phrase is usually "but should you?"

You could create an installation package that does everything you need to install the site on a PC. It'll be a little more complex as you'll need to set up IIS.

You'll lose the ability to deploy a change once and have it reach all users like you usually would get with a web app. This is h same issue if you deploy a desktop app of course.


问:
How to develop line-of-business tablet apps as a .NET developer?
My company has a lot of experience in .NET development, and one of our products in an ERP system. Recently, a customer asked us if we could provide a tablet interface to that system, i.e., a software that allows the customer to view product information and create orders on a tablet.

Of course, we are not thrilled about the idea of investing a lot of time and money into learning Objective-C, purchasing Mac development workstations, paying fees to Apple, etc. just for this one project (we might be able to sell the app to a few additional customers afterwards, but the market is very small, since it would only be useful for existing customers of our ERP system).

So, what should we do? As far as I can see, we have the following options:

Write a "plain old Windows application" (WPF) and run it on a Windows 7 tablet, such as the Samsung Slate or Acer Iconia.

Drawbacks: Heavy, expensive devices with short running time (as compared to "real" tablets).

Wait for Windows 8 ARM-based tablets and write a Metro (WinRT) app.

Drawbacks: Wait for at least one year; it's unclear whether Windows 8 ARM will support installation of custom B2B apps without going through the app store.

Use mono for Android and write a .NET app for Android.

Drawbacks: Yet another UI library (different from WPF and Silverlight); some providers disallow sideloading of apps.

So far, options 1 and 3 seem to be the most realistic. Did I miss any obvious drawbacks or advantages? Is there another option that I haven't considered yet? Have you been in a similar situation and (successfully) chosen one particular option?

答:
That last comment says it all really: 'Dot Net could only be of value on the server side' - perhaps Microsoft should have called it .Not?
Or .WindowsOnly?

You can't even write Windows RT client-side apps in .Net.

It is true that in order to play in the cross platform game, your business logic and data services written in .Net, have to live on a windows server and expose a Web friendly API. The latest ASP.Net Web API is almost industrial strength in April 2013. This will allow you to expose your .Net objects as JSON so that JQuery/JS client-side apps can integrate easily.

On the client side, you cannot use .Net. You have to write all your UI code in HTML/CSS/JQuery and your logic using JS with perhaps Knockout for data oriented binding.

For us .Net developers, simply drawing our user interface WITHOUT HAVING TO WRITE MARKUP is the Nirvana of developing LOB apps. Whoever comes up with a client side .Net framework which works as well as VS/.Net/WinForms/C#/VB.Net will rule the world - and NO - in my opinion Mono is nowhere (no support from 3rd party component vendors) near VS/.Net/WinForms.


答:
First understand what it's meant to be doing - without that it's likely to be gibberish.  Speak to the users, read the manual, whatever.

Then hit run and start walking the code for what seem to be the key functions.

Title: How do you dive into large code bases?

Body:
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?


答:
I think warnings, which are not treated as errors, are useless. You get tons of them, therefore nobody bothers to look at them, and they miss their purpose.

My suggestion is to fix them all, and start treating them as errors.

Fixing them looks scary, but I think it can be done. A good programmer that would pick up this work will very soon figure out the way to deal with each warning, and will handle it very mechanically and quickly.

We did a similar project in my company, and it did work - we now have no warnings in the part of the code where it's important to us, and I'm talking about many thousands of files (don't know how many warnings).

This must be immediately followed by treating warnings as errors. Once a part of your code is warning-free, change the compilation flags for this part, and let no new warnings enter. If you fail to do that, you'll find new warnings pop up like mushrooms, and your work will be wasted.

One concern you may have is introducing bugs as a result of fixing the warnings. This is especially likely because the programmer fixing the warnings probably doesn't know most of the code he's changing. However, most changes would be very safe - e.g. adding a function prototype or a cast.

Title: How to deal with warnings in a legacy project

Body:
I work on a C++ project that generates bajillions of warnings. Most of the warnings appeared after the code was written:

Initially the project used Visual C++ 8, soon switching to 9, but there is little difference in the generated warnings. Warnings were either fixed or silenced, so there were no warnings then.

Then a 64-bit target was added. It generated a huge amount of warnings, mainly because of sloppy use of types (e.g. unsigned vs. size_t). No one bothered, or had time, to fix them once the code worked for the purpose.

Then support for other platforms using GCC (4.5 and 4.6, some 4.4 initially) was added. GCC is much more picky, so it generated many more warnings. Again nobody bothered, or had time, to fix them. This was complicated by the fact that GCC didn't have a pragma to silence a warning in particular bit of code until 4.5, and according to the documentation it is still not what one would need.

In the mean time some deprecated warnings popped up.

So now we have a project generating thousands of warnings. And I can't even say from how many places, since even .cpp files are compiled several times by different compilers and warnings in headers get printed over and over.

Is there a best practice for cleaning up something like that? Or at least some positive experience dealing with it?


问:
Objective-C class cluster pattern
I have many sublcasses of one class. I choose concrete class based on type (simple enum). I like idea of class cluster. Should i use it or just create factory class (but each class in objective-c is actually a factory)?

What is the difference between factory pattern and class cluster pattern.
When to use it in your code and why?

答:
There isn't really any difference; a class cluster is a specific implementation of the Factory pattern. In the class cluster, the initialiser is used as the factory method to decide what instance to return.

Stylistically, the class cluster will be familiar to users of your API because it's common in the Apple frameworks: the collection classes, number classes and others make use of the pattern. It also satisfies the higher-level pattern of Smalltalk and Objective-C where the class object is itself a factory for its instances.

In addition the class cluster means fewer things to remember: rather than thinking "I have to make a ThingFactory then call [factory thingForCase: foo]" they just look at the initialiser for Thing, which is what you'd probably reach for by default.

There is a situation in which you would reach for a more "classic" implementation of Factory, which is (as discussed in the comment thread) where the objects you might return won't necessarily be subclasses of a common parent. In the class cluster pattern, there's a common superclass and client code treats whatever object is returned as an instance of that superclass. If this restriction in the type hierarchy is not suited to your case then a class cluster is not going to work.

Title: Objective-C class cluster pattern


问:
How do I prove to management that our programmers could work more productively?
Backstory

I graduated less than a year ago with a degree in Computer Science (with extra courses in software engineering), and another degree in Software Engineering. I'd like to think that I'm familiar with modern software development methodologies (CI, Scrum, XP, etc).

The problem

I got my first (and current) job at a medium sized game development company. The company has been around for several years, has multiple successful titles under its belt, and is full of talented and dedicated people. However, software development happens in an entirely ad hoc way. We use SVN and a bugtracker, but beyond that there's very little planning, no automated testing, and you'd be hard pressed to find a UML diagram anywhere in the office.

I can think of two possible reasons for this:

Programmers are simply not given enough time to do things properly. Sadly, upper management has a tendency to set deadlines without consulting the programmers, which has led to many an all-nighter.

The programmers themselves lack the education / motivation to employ proper techniques.

The question

I recently spoke to management about this, and I was encouraged to suggest alternatives. I figure the first thing to do would be to rule out the second possibility listed above: that is, give management some evidence that if the programmers were given more breathing space, they could become much more productive. However, I'm not quite sure how to go about that. My best idea so far is to conduct a survey among programmers about what software development methodologies they know, as well as their attitudes towards code quality and such.

tl;dr

How can I assess whether our programmers are able/willing to employ modern software development methods, and prove to management that this would lead to increased productivity?

EDIT

I obviously failed to bring my point across properly, so let me elaborate on the situation a little.

First, I am fully aware that this looks like a bright-eyed fresh grad trying to save the world with his l33t education and changing the wicked ways of those grumpy old fossils who just don't know any better. I also understand that there is always a difference between theory and practice, and what they teach you in school is never what happens in real life. That is exactly why I'm being incredibly cautious here, trying to get a feel for the current situation instead of charging in going "Hai guise, let's all do teh unit tests from now on!"

Second, @psr raises a very good point. Let me name some of the reasons why I think that there is room for improvement:

Our senior developer, who's a bit of a maverick but ultimately a skilled and reasonable guy, agrees that at this point in the company's history, we should have more sophisticated and repeatable development processes in place.

One of the programmers who's much more experienced than me and has used modern methods agrees with me that we could be more productive if we used some of them.

In some cases, throwing features together during an all-nighter and then hunting down all the bugs takes a ridiculous amount of time; I cannot imagine that doing things any other way could be any worse.

The lack of planning, design, refactoring and documentation leads to poor code quality. Perhaps more importantly, it leads to programmers forgetting how their own code works in a matter of months (while they're still working on the same project!), and no way to find out apart from trial and error or wading through the spaghetti.

Even management suffers, as the only quantifiable measure of progress in a project is the number of unresolved bugs. But since anything is liable to break at any time (due to the reasons above), this is a very unreliable figure.

Third, I don't actually believe that my colleagues lack the knowledge of modern methods or the willingness to use them, it's just that at this point, I cannot rule it out as a possibility. Which is kind of the reason why I came here asking what's the best way to find out what they know (besides lengthy personal interviews, obviously).

Fourth, don't take those comments about UML and automated testing too seriously, they were just examples. The fact is, code is produced on the immediate whims of designers/upper management without any kind of software design, and only ever tested by a couple guys pressing buttons to see if anything breaks. Perhaps I'm still wearing my university-issued rose tinted glasses, but that strikes me as garage-development at its finest.

tl;dr

I'm trying really hard not to be arrogant about this, but both my fellow programmers and management seem to be expressing a desire for more predictable and productive ways of developing software. How can I find a solution that could make for an easy transition?

答:
I think there are some important aspects regarding productivity (I am not an expert in management, so this is just my 2 cents).

Here is a simplified scenario to illustrate my points.

Suppose you have 2 packages of features (X and Y) to implement, and that it takes 6 months to complete the first package X (first release).
Suppose also that package X is used by later modules (e.g. Y).

I think often programmers say "I do not have time to do it properly" because when they write X they know X is going to be reused in Y and want to clean up the code and the design in order to make it more robust and reusable. Even if the code is not going to be reused, they know that a clean code will save them a lot of time if they have to fix bugs later. That's also what you learn in school and I think these are good principles.

But from a management point of view (i.e. in the industry, the so-called real world), release 1 is the one thing that is 100% sure, and any extra time spent on X after X is good enough for release 1 is considered a waste of time. The customer buys working software, not clean code.

Six months later, when working on package Y that makes heavy use of X, you wish you had produced proper diagrams and design, you wish you had made your design more extensible, and you wish you had done this six months earlier, when you had the whole problem still in your mind.

Anyway, now Y needs to be done and so X needs to be extended (extra work). While quickly adding extensions to X, X starts to get messy and new bugs appear.
So, instead of

7 months for release 1 (doing X properly), and

7 months for release 2 (doing Y properly, with little work on X),

you have

6 months for release 1 (minimal X implementation that does the job), and

9 months for release 2 (implementing Y, implementing workarounds and bug fixing on X).

In the second scenario you have lower productivity on average but from a management point of view, you can only plan in the short / middle term. You basically do not optimize what you might not need: you cannot plan work on both release 1 and 2, if you are not 100% sure whether there is going to be release 2.

I think this is a bit of a paradox: managers prefer to save one month on release 1 and spend two extra months on release 2 because the extra cost on release 2 is less certain than the saving on release 1.

So, I think much of the frustration of many programmers that "there is no time to do things properly the first time, but there is always time to fix them later" (and the resulting loss of productivity) is inherent in the way projects are planned: since we do not know how the market will be in 2 years from now, we cannot make optimal plans and we must accepts a loss of productivity.


问:
Creating an account to receive sensitive information on a mobile device
I am developing an Android application for my final year project which allows the holder of a mobile device to receive a text notification containing potentially sensitive information from a server.

My question is this, if a User downloads the application, what is a suitable way for them to create an account / log in on my server to receive notifications from it?

I was thinking:

Application

Open application

Click Register

Fill out fields (Name / Address / ID / Phone no.)

Send to server

Display "Account Pending"

If approved, send positive message, begin receiving notifications from server.

If denied, send negative message, if User tries to log in with that account, the App will inform them that it was rejected.

Server

Add received information to a "Pending Account"

When an Admin comes online, they can review the information (How can they be sure the person is who they say they are?)

If the account is approved, the details are moved to a normal User account, otherwise moved to rejected accounts.

I can't think of another solution which would fit this problem. If anybody knows of a patterns or design I appropriate to hear from you.

答:
Modifying the answer, according to the conversation in the comments.

You mentioned this is security-sensitive, and thus you cannot trust people from the Internet without a strong security token. Assuming the people have secured work emails (connection between the email client and server is never plain text), you can probably create the user accounts centrally on the server, according to their required privileges, and send the first-time passwords to them via email. They can then log in to the system using their email address and the password. Normally they also need to change the password immediately. You may decide to activate their privileges only after they log in for the first time and change their password.


问:
Why didn't == operator string value comparison make it to Java?
Every competent Java programmer knows that you need to use String.equals() to compare a string, rather than == because == checks for reference equality.

When I'm dealing with strings, most of the time I'm checking for value equality rather than reference equality. It seems to me that it would be more intuitive if the language allowed string values to be compared by just using ==.

As a comparison, C#'s == operator checks for value equality for strings. And if you really needed to check for reference equality, you can use String.ReferenceEquals.

Another important point is that Strings are immutable, so there is no harm to be done by allowing this feature.

Is there any particular reason why this isn't implemented in Java?

答:
In Java, there is no operator overloading whatsoever, and that's why the comparison operators are only overloaded for the primitive types.

The 'String' class is not a primitive, thus it does not have an overloading for '==' and uses the default of comparing the address of the object in the computer's memory.

I'm not sure, but I think that in Java 7 or 8 oracle made an exception in the compiler to recognize str1 == str2 as str1.equals(str2)


问:
How to learn/become capable of thinking out of the box?
In every problem solving there's always people who think differently, who come with a 6th option when only 5 were suggested by others, who think "out of the box". Please tell how one can achieve such ability? And what it takes to achieve it?</p>

答: A lot of it either comes with practice, or is simply innate: some people are more creative than others. But I think a big part of outside-of-the-box thinking comes from having a breadth of knowledge, and knowing (or having the experience to know) when to apply that knowledge to different problems.</p>


答:
I guess it's just consistency, or "principle of least astonishment". String is an object, so it would be surprising if was treated differently than other objects.

At the time when Java came out (~1995), merely having something like String was total luxury to most programmers who were accustomed to representing strings as null-terminated arrays. String's behavior is now what it was back then, and that's good; subtly changing the behavior later on could have surprising, undesired effects in working programs.

As a side note, you could use String.intern() to get a canonical (interned) representation of the string, after which comparisons could be made with ==. Interning takes some time, but after that, comparisons will be really fast.

Addition: unlike some answers suggest, it's not about supporting operator overloading. The + operator (concatenation) works on Strings even though Java doesn't support operator overloading; it's simply handled as a special case in the compiler, resolving to StringBuilder.append(). Similarly, == could have been handled as a special case.

Then why astonish with special case + but not with ==? Because, + simply doesn't compile when applied to non-String objects so that's quickly apparent. The different behavior of == would be much less apparent and thus much more astonishing when it hits you.

Title: Why didn't == operator string value comparison make it to Java?

Body:
Every competent Java programmer knows that you need to use String.equals() to compare a string, rather than == because == checks for reference equality.

When I'm dealing with strings, most of the time I'm checking for value equality rather than reference equality. It seems to me that it would be more intuitive if the language allowed string values to be compared by just using ==.

As a comparison, C#'s == operator checks for value equality for strings. And if you really needed to check for reference equality, you can use String.ReferenceEquals.

Another important point is that Strings are immutable, so there is no harm to be done by allowing this feature.

Is there any particular reason why this isn't implemented in Java?


答:
Java doesn't support operator overloading, which means == only applies to primitive types or references.  Anything else requires invocation of a method.  Why the designers did this is a question only they can answer.  If I had to guess, it's probably because operator overloading brings complexity they weren't interested in adding.

I'm no expert in C#, but the designers of that language appear to have set it up such that every primitive is a struct and every struct is an object.  Because C# allows operator overloading, that arrangement makes it very easy for any class, not just String, to make itself work in the "expected" way with any operator.  C++ allows the same thing.


问:
Customer Requirements Contains Equations that Cancel to Nothing
I have a project where the customer requirement specifies a report and contains mathematical equations for the contents of some of the columns on that report. One of the columns on this report is a running total which starts at a opening value, and which 'should' remain at that opening value all the way down the report because the other stuff balances out. I.e. if something had gone missing, the value would change and the customer would see that there is a problem.

The reason I quoted the 'should' in that last paragraph is because the spec defines an equation for this column, and I can mathematically prove that it cancels out to 'the value from the previous row'. In other words, the value will never ever change from the opening value.

So my options are:

Implement the equation as spec'd, I suspect the interpreter will not resolve the equation so there will be a performance hit

Do some cancelling out, and implement the column value as 'value from the previous row'

Send the question back up the chain to the customer and risk missing the deadline because of several days lost to bureaucracy and impromptu math 101 lessons to explain the difference between "yeah, it'll never change, it's there just in case" and "it. will. never. change."

I've pretty much decided what I'm going to do, but I thought it was an interesting question. What do you think is the professional thing to do?

答:
Do the easier of implementing the equation specified in the formula or spitting out the previous row's value, incorporating a prominent comment in the code explaining why it is as it is.

At the same time, send your question back up the chain.  If they get back to you with a spec change in time to implement it, then implement it.  If not, your butt's still covered because your output meets the original spec.


答:
James Gosling, the creator of Java, explained it this way back in July 2000:

I left out operator overloading as a fairly personal
  choice because I had seen too many people abuse it in C++. I've spent
  a lot of time in the past five to six years surveying people about
  operator overloading and it's really fascinating, because you get the
  community broken into three pieces: Probably about 20 to 30 percent of
  the population think of operator overloading as the spawn of the
  devil; somebody has done something with operator overloading that has
  just really ticked them off, because they've used like + for list
  insertion and it makes life really, really confusing. A lot of that
  problem stems from the fact that there are only about half a dozen
  operators you can sensibly overload, and yet there are thousands or
  millions of operators that people would like to define -- so you have
  to pick, and often the choices conflict with your sense of intuition.


问:
How to deal with user interface design and respective feature support in Agile development?
In an Agile development process usually the main focus is on User stories, but sometimes a single requirement may span several user stories.

For example, the client may request a search page for all users in a forum, and there are several actions that can occur on each user such as ban user, delete user, reset Password, etc.

We may divide this feature into at least 4 user stories:

Search for users

Ban user

Delete user

Reset password

How would the user interface designer implement such a user interface? Should he/she work on the first user story and then start incrementing more features to the UI? However, I think the final UI will be messed up!

If he decides to work on the whole feature (search + actions), what if the actions where of low priority and would be implemented several iterations after the search functionality was done?

答:
Take it iteratively.  You're working directly with the users, right? So it should never really be a mess.

First do the search page.  You and the users should keep in mind that they'll want to be able to do actions on the results.  Do the users like it?  OK, you've got your search.

Now add the "Change Password" (or whatever is next in priority).  Oops, we need to change the search page a little--well, change is often part of the game. Do the users like it like the results?  Good.

Now add the next item, and the next...

The agile approach says you always have feedback right away, so you should be good.

That said, there's no real reason why you might not be able to attack 2 of these stories in the same iteration (adding delete user AND ban user).  The key is to always be working with the customer to make sure it's right.

You're often (always?) going to end up with users thinking of something else they want to do from that search screen after your original "design" is done and implemented.  So, you'll end up modifying it at some point anyway.  Just approach the whole thing with that expectation and you should be good.


问:
Summary of differences between Java versions?
What are the major differences in between Java version in terms of software development? Where can one find a summary of the most important changes related to programming?

The Release Notes such as http://www.oracle.com/technetwork/java/javase/releasenotes-136954.html can be hard to read.

For example there is new code structure "for each" in Java 1.5.

答:
This is a summary of the excellent Wikipedia article about the Java version history. It is highly selective (and biased on what I know and use), otherwise it would simply turn out to be a copy of the article.

The bold parts are what really brought the language forward as a whole. As you see, not every release has bold parts.

Java 11

JSR 384, what's new

Language changes:

Local-Variable Syntax for Lambda Parameters

Library changes:

JEP 321 Http Client standardized

Java 10

JSR 383, what's new

Language changes:

Local variable type inference (var keyword)

Java 9

JSR 379, what's new

Language changes:

further continuation of Project Coin (small language improvements)

Library changes:

Java Platform Module System (jigsaw)

modularization of the platform itself

makes modules a first-class citizen meant to replace the messy classpath with modules with real dependency information

Other changes:

People seem to have gotten over the 1.x naming convention, almost no one calls this "Java 1.9".

Java 8 (a.k.a 1.8)

JSR 337, what's new

Language changes:

lambda expressions (JSR 335, includes method handles)

continuation of Project Coin (small language improvements)

annotations on Java types

Library changes:

Improved Date and Time API

Java 7 (a.k.a 1.7)

JSR 336, features and enhancements

Language changes:

Project Coin (small changes)

switch on Strings

try-with-resources

diamond operator

Library changes:

new abstracted file-system API (NIO.2) (with support for virtual filesystems)

improved concurrency libraries

elliptic curve encryption

more incremental upgrades

Platform changes:

support for dynamic languages

Java 6 (a.k.a 1.6)

JSR 270. features and enhancements

Mostly incremental improvements to existing libraries, no new language features (except for the @Override snafu).

Java 5 (a.k.a 1.5)

JSR 176, features and enhancements

Language Changes:

generics (that's the big one)

annotations

enum types

varargs, enhanced for loops (for-each)

Library changes:

concurrency utilities in java.util.concurrent

Java 1.4

JSR 59

Language changes:

the assert keyword

Library changes:

regular expressions support

NIO

integrated XML handling

Java 1.3

Mostly minor improvements, really.

Platform changes:

HotSpot JVM: improvement over the original JIT

Java 1.2

Language changes:

the strictfp keyword

Library changes:

a unified collections system

Swing as a new UI-System on top of AWT

Platform changes

a real JIT, greatly improving speed

Java 1.1

Language changes:

inner classes

Library changes:

AWT event changes

JDBC, RMI

reflection

Java 1.0

Initial release, everything is new ;-)

ContentLicense: CC BY-SA 4.0


答:
Using the ASP.NET hostable web core will allow you to host the ASP.NET runtime in your application. This means you can create your own local webserver, running ASP.NET MVC, webforms, or any other frameworks you choose to use. Have a look at this blog entry.

This is separate from IIS and you do not need to need to set up or configure IIS; simply having the .NET framework installed is sufficient.

The way you would likely distribute this is as a folder installed to the hard drive.

Title: Reuse MVC4 codebase / deploy MVC4 as standalone desktop application?

Body:
We have an MVC4 application that we would also need to distribute as a standalone (no network connectivity) desktop application. Rather than rebuild the HTML/JS front-end we would like to reuse that so in essence we're distributing a self-hosted HTML-view-based .NET MVC application. What we roughly envision is: MVC4 .NET DLL + JS libraries + Self-hosted HTTP core + self/embedded browser view. For this standalone desktop app, we're only concerned with Windows OS.

Question: Is that practically doable or just a theoretical idea? How would we practically go about achieving that? We are attempting to minimize codebase fragmentation (and duplicate maintenance). We anyways have to support IE for the "online" version of the MVC app.

To Clarify: The user experience we would like to have is:

Single large .exe file that encapsulates all resources within it

Double clicking it launches a rectangle window within which the HTML app is rendered. This would be similar to how iOS apps have an "HTML view" which uses the OS's in-built HTML renderer (on Windows I assume it's IE?)


答:
The first user story can be the design of the whole interface -- they don't have to design just one piece of it. It is the design as a whole that adds business value.

That being said, I see at least two distinct features here: the ability to search for users, and the ability to perform a function on one or more users. The designer could tackle each of those searately if that makes more sense.

Remember: the goal is to deliver quality software, it's not to blindly follow some methodology. Ask yourself whether breaking the design up into pieces helps or hinders that goal. There are no scrum police, only happy or dissatisfied customers.

Title: How to deal with user interface design and respective feature support in Agile development?

Body:
In an Agile development process usually the main focus is on User stories, but sometimes a single requirement may span several user stories.

For example, the client may request a search page for all users in a forum, and there are several actions that can occur on each user such as ban user, delete user, reset Password, etc.

We may divide this feature into at least 4 user stories:

Search for users

Ban user

Delete user

Reset password

How would the user interface designer implement such a user interface? Should he/she work on the first user story and then start incrementing more features to the UI? However, I think the final UI will be messed up!

If he decides to work on the whole feature (search + actions), what if the actions where of low priority and would be implemented several iterations after the search functionality was done?


答: If the goal of the formula was to check for missing values, construct a test that should verify that the software can detect that a value is missing. If the formula is wrong, the test will not be successful. Then it can be flagged, investigated, and fixed.</p>

Title: Customer Requirements Contains Equations that Cancel to Nothing

Body:
I have a project where the customer requirement specifies a report and contains mathematical equations for the contents of some of the columns on that report. One of the columns on this report is a running total which starts at a opening value, and which 'should' remain at that opening value all the way down the report because the other stuff balances out. I.e. if something had gone missing, the value would change and the customer would see that there is a problem.

The reason I quoted the 'should' in that last paragraph is because the spec defines an equation for this column, and I can mathematically prove that it cancels out to 'the value from the previous row'. In other words, the value will never ever change from the opening value.

So my options are:

Implement the equation as spec'd, I suspect the interpreter will not resolve the equation so there will be a performance hit

Do some cancelling out, and implement the column value as 'value from the previous row'

Send the question back up the chain to the customer and risk missing the deadline because of several days lost to bureaucracy and impromptu math 101 lessons to explain the difference between "yeah, it'll never change, it's there just in case" and "it. will. never. change."

I've pretty much decided what I'm going to do, but I thought it was an interesting question. What do you think is the professional thing to do?


问:
Is path in Set-Cookie URL encoded?
I'm writing some code that sets cookies and I'm wondering about the exact semantics of the Set-Cookie header. Imagine the following HTTP header line:

```<code>Set-Cookie: name=value; Path=/%20
</code>```

For with path does this set the cookie? / or /%20(unescaped) (/%20 or /%2520 escaped)?

The reason I'm asking is that I should support non-ASCII paths. Since HTTP header must only be ASCII my plan was to URL escape the path value but the HTTP specification is not as clear as I'd hoped for.

Edit

I know what Path is supposed to do. My question is: Is the value interpreted as percent encoded or not?

答:
Syntax

setcookie(name,value,expire,path,domain,secure)

path

Optional. Specifies the server path of the cookie
  If set to "/", the cookie will be available within the entire domain. If set to "/test/", the cookie will only be available within the test directory and all sub-directories of test. The default value is the current directory that the cookie is being set in.

Source: PHP setcookie() Function

There is also a great existing SO answer around allowed characters in cookies (it talks about ASCII characters)

What that document doesn't remember to say, because Netscape were terrible at writing specs, was that control characters (\x00 to \x1F plus \x7F) aren't allowed, and support for non-ASCII characters is left unspecified.

What browsers do:

in Opera and Google Chrome, non-ASCII characters are encoded into cookies with UTF-8;

in IE, the machine's default code page is used (locale-specific and never UTF-8);

Firefox (and other Mozilla-based browsers) use the low byte of each UTF-16 code point on its own (so ISO-8859-1 is OK but anything else is mangled);

Safari simply refuses to send any cookie containing non-ASCII characters.

So in practice you cannot use non-ASCII characters in cookies at all. If you want to use Unicode, control codes or other arbitrary byte sequences you must use an ad-hoc encoding scheme of your own choosing. Most popular is UTF-8-inside-URL-encoding (as produced by JavaScript's encodeURIComponent).

Title: Is path in Set-Cookie URL encoded?


答:
There is no box!

There is a specific problem to solve, and a set of constraints which might apply. Work out what the problem is (think abstractly and in real terms), defining it in both specific topic-based terms, and in more general terms.

Examine each of the constraints (don't make assumptions) to see if, when, and to what extent they might apply. Look at the problem from the perspective of who it affects (don't forget the goal) as well as from behind the scenes.

Don't make assumptions.

If you assume certain things are true when they're not, you'll prevent yourself from examining different perspectives. Also challenge existing decisions/assumptions that others have made - there might be a good reason for it, or there might not, or there was one that no longer applies.

Think abstractly.

Learn to see things as patterns and in abstract terms. When you spot a pattern, consider similar things and see if you can apply actions from it to the current thing. If your subject area has named patterns, learn them - but don't treat them as cookie cutter solutions.

Don't think abstractly.

Always try to see things as they are too - remember that "users" are people, and they're not always logical or rational. Practise empathising with the people using what you create.

Don't forget the goal.

Sometimes it's easy to get bogged down with a particular target/implementation (e.g. "how do we fit these X controls into the UI?") instead of remembering the real goal (such as "how do we allow the user to do Y?")

Never stop learning.

General knowledge can be a great source of inspiration - a lot of problems have been solved by someone already - the more you know the more you might remember something applicable to the current situation.

Be a good programmer, not just a good at [programming language].

Don't be scared to learn multiple technologies and techniques - even multiple "overlapping" languages can help you to see things in different terms, but a good variety of different ones may help more. Of course pick a few areas to specialise/master, but also make sure you have a decent grounding in general concepts, which you can gain by learning multiple different languages,

Don't assume someone is too inexperienced to help.

Sometimes people that appear not very knowledgeable, or that have never programmed, can appear to be useless for a programming problem - but that doesn't mean you should ignore them. Everyone has different perspectives and skill-sets, and might provide a unique insight that spring-boards you to a solution.

Young kids can especially be a good source of an "untainted" perspective that can be inspirational.

Title: How to learn/become capable of thinking out of the box?

Body: In every problem solving there's always people who think differently, who come with a 6th option when only 5 were suggested by others, who think "out of the box". Please tell how one can achieve such ability? And what it takes to achieve it?</p>


问:
Mapping a legacy database to ORM using wrapper classes
I want to use an ORM with a legacy database, but I don't want to expose some of the underlying data types. For example, some of the columns are nullable doubles or floats and I want my domain model to use non nullable decimals.

It seems to be impossible to have Entity Framework automagically cast between these types, and maybe for good reasons. I also want to be able to use enums and so far I have not found any method that don't look like ugly hacks to make this possible.

My idea is simply to use wrappers, where I have table-like classes mapped to the database but wrap them in "real" domain classes for use in code. My question is simply if you have any thoughts about this approach or if you have any tips. I have no experience in mapping a legacy database to an ORM so any comments or suggestions are appreciated.

Note: I've only looked at Entity Framework so I have no knowledge about the capabilities of other ORMs, such as NHibernate.

答:
I haven't used EF much, but have used NH quite a bit.

NH typically works on a model (or entity if you prefer) per table basis. That is, there is one class per table in the database. Most ORMs have a way to map database types to C# types. For example, it would be possible to convert a varchar(max) column which contains 'true' and 'false' to a bool in a C# class.

You can also take this one step further: If your business model relies on Customers (the C# class), but the data is in one or more DB tables, you can use combine those mapped classes into the one model (CustomerInfo + AddressInfo = CustomerClass).

Creating and Testing a Custom NHibernate User Type


答:
I'd wrap your SQL data access calls as stored procedures then, you can expose a different datatype in the sproc results, casting within the procedure if required.

Then your data access becomes like an API, you won't need all the nasty ORM mapping stuff, and just use it to read and write the "DB API" keeping all the internal structure of the DB hidden.

Title: Mapping a legacy database to ORM using wrapper classes

Body:
I want to use an ORM with a legacy database, but I don't want to expose some of the underlying data types. For example, some of the columns are nullable doubles or floats and I want my domain model to use non nullable decimals.

It seems to be impossible to have Entity Framework automagically cast between these types, and maybe for good reasons. I also want to be able to use enums and so far I have not found any method that don't look like ugly hacks to make this possible.

My idea is simply to use wrappers, where I have table-like classes mapped to the database but wrap them in "real" domain classes for use in code. My question is simply if you have any thoughts about this approach or if you have any tips. I have no experience in mapping a legacy database to an ORM so any comments or suggestions are appreciated.

Note: I've only looked at Entity Framework so I have no knowledge about the capabilities of other ORMs, such as NHibernate.


问:
Custom use of Authorization header in a REST API
I'm building a REST api where clients are authenticated using client certificates. A client in this case is not an individual user, but some sort of a presentation layer. Users are authenticated using a custom approach and it's the responsibility of the presentation layer to see that this is properly done (note: I know this is not the proper approach, but the api is not public).

I would like to pass the user name for each request (not the password), but I'm not sure where to do this. Would it be a good idea to use the Authorization header?

答:
I wouldn't recommend that you make non-standard use of a standard HTTP header. Primarily because it can be misleading to other developers that know how the Authoriziation header is meant to be used in HTTP authentication, but also to avoid any potential issues with other parts of your stack having conflicting awareness of the same request header.

Whatever the case, there's nothing preventing you to use a custom, non-standard X-Authorization-User header, specifically for your purposes.


问:
What to do when a client asks for something unreasonable (from my point of view)
I'm a freelance programmer and recently I finished a website, it all works fine but there was one user that complained to my client that he couldn't log in. This problem was clearly a cookie-restriction/old browser one (I couldn't create the problem myself and hunderds of users are working with the website just fine)

Now my client said: I've paid you to make something and somebody complains; so you didn't do your work correctly.

What can I do in this situation and how do you guys handle this?

答:
If you haven't already done so, define the minimum system requirements of your website, e.g.

supported browsers¹,

minimum display size,

required cookie permissions,

etc.

If the user did not satisfy the minimum system requirements, it's not your fault that it didn't work for him. Investigate the issue, prove that the minimum system requirements were not satisfied and send the client an invoice for the time you spent doing this.²

Of course, in some cases it's not so easy: You might be convinced that the problem lies "on the user's side", but you might not be able to prove it without putting a lot of effort into it. In that case, you should talk to your customer:

I have performed some tests, and I'm pretty sure that the problem is a weird firewall configuration/a buggy IE plugin/etc. However, to prove this, I'll have to put a lot of effort into it. If I do that and it turns out that the fault was not on my side, I will have to send you a bill for the work done by me. Are you sure that you want me to continue investigating this issue?

¹ This doesn't mean it won't work with other browsers, it only limits your warranty to these browsers. Usually, the customer will understand that you cannot test your web site extensively with every browser out there. Ideally this should be cleared up-front:

Support for IE8-10, FF12-19 and Safari 5 is included in the offer. IE7 can be included for an additional $xxx, IE6 for an additional $xxxx.

² Sending an invoice is a very powerful sign: Even if the customer complains and you end up canceling the invoice as a goodwill gesture, the client learns that unjustified complaints can cost money.


答:
Resolve the complaint irrespective of how many users were successful.  Also ensure that, through each user complaint, you record what went wrong for the future.

As a programmer, you have to consider cookie-restriction/old browser and properly account for it.  There is no acceptable solution in which a 'too bad; upgrade!' is acceptable unless specified by your client.

This may be a learning opportunity in which you hash such details out with your clients to ensure, if there is the possibility, it is covered and there are no surprise 'gotcha' situations.

Title: What to do when a client asks for something unreasonable (from my point of view)

Body:
I'm a freelance programmer and recently I finished a website, it all works fine but there was one user that complained to my client that he couldn't log in. This problem was clearly a cookie-restriction/old browser one (I couldn't create the problem myself and hunderds of users are working with the website just fine)

Now my client said: I've paid you to make something and somebody complains; so you didn't do your work correctly.

What can I do in this situation and how do you guys handle this?


答:
I feel like I say this a lot.  Agile does not mean you need to put blinders on to ignore the future and design yourselves into a corner.   Agile is about how you deliver functionality, and has very little to do with how you design functionality.

In other words, it's okay to look as far into the future as you want when creating your design, as long as it doesn't postpone the delivery of functionality in the short term.

What that means in your specific example is that you go ahead and design the user interface such that it will be easy to add actions later.  However, if working on getting the actions design right would delay delivery of basic user search by an iteration, it's better to do a design without actions first, assuming a search without any actions has value to the customer.

The question to ask yourself is, "Is this design work delaying my first delivery?"  Most of the time, the answer will be no.  You have to do a design anyway, all you're changing is some design criteria.


答:
There's no single answer to this. It helps if you mentally exercise thinking out of the box regularly, even in mundane day-to-day activities.

Reversing Assumptions
As one of the many possible approaches, you could try focusing on reversing inherent assumptions of a solution or problem:

You start with the problem. Think of an easy solution, a solution that anyone could think of. Then ask yourself: What are the assumptions underlying this solution? Or what are the assumptions on the problem? Now take one (or several) of those assumptions and ask yourself: what if dropped/reversed this assumption? Or what if instead of directly addressing some requirement, I could satisfy it as a side effect of another solution?