答:
Its an interesting question - there is a strong argument that most decent developers  should understand how to properly structure a relational database, that is to say that they should be capable of producing a normalised schema and - based on experience and common patterns - to make reasonable decisions as to how data should be structured stored (for me its mostly self evident, but I know that not everyone sees it that way).

Further, if you look at Entity Framework Code-first that suggests that the same thought that goes to building a low level data model will product a reasonable schema - or at least hint at one.

So no, I don't particularly think that you need a database expert to design a database schema - at least not for small and medium size databases (which are the things I've worked on).

The issue is that designing a good (or at least adequate) schema is not the whole story - especially not if the database has to scale. It seems to me that the "added value" brought by a DBA is in getting the things other than the basic schema right - indexes, configuring storage, maintenance of the database (keeping file sizes in check, rebuilding indexes, etc), being smarter with users and roles and so on and so forth.

A good programmer should bring a diverse portfolio of skills - should be more than an [insert langugage of choice] coder and I would include understanding of databases in that portfolio.


问:
Do I need to test everything?
I'm going to start my first real project in Ruby on Rails, and I'm forcing myself to write TDD tests. I don't see real advantages in writing tests, but since it seems very important, I'll try.

Is it necessary to test every part of my application, including static pages?

答:
Just to add to all the already excellent answers, here's my thinking on what to test, and what not to test:

Do test:

business logic

application logic

functionality

behaviour,

so, everything, really, except:

Do not test:

constants

presentation

So there's no point in having a test that says:

```<code>assert wibble = 3
</code>```

and some code that says

```<code>wibble = 3
</code>```

And  there's also no point in testing presentational things, like whether the icon is in perywinkle blue, what font you've used for headings, and so on...

So, you ask, "should I test static pages", and the answer is:  you test them insofar as they are part of your site's functionality, business logic, or behaviour.

So, in our app, we have a test that checks that the terms & conditions are available from every part of the site - for anonymous users, for logged-in users, from the dashboard, inside app screens etc.  It just checks that there's a link called "terms and conditions" on each page, that the link works, and then the test says that when it arrives on the page, it "looks like" the Ts & Cs - just enough to reassure yourself it's the right page, without "testing a constant", or "testing presentation"... so you could check that the text is correct, for example, without checking the particular font size or text layout...

ContentLicense: CC BY-SA 3.0

Title: Do I need to test everything?

Body:
Just to add to all the already excellent answers, here's my thinking on what to test, and what not to test:

Do test:

business logic

application logic

functionality

behaviour,

so, everything, really, except:

Do not test:

constants

presentation

So there's no point in having a test that says:

assert wibble = 3

and some code that says

wibble = 3

And  there's also no point in testing presentational things, like whether the icon is in perywinkle blue, what font you've used for headings, and so on...

So, you ask, "should I test static pages", and the answer is:  you test them insofar as they are part of your site's functionality, business logic, or behaviour.

So, in our app, we have a test that checks that the terms & conditions are available from every part of the site - for anonymous users, for logged-in users, from the dashboard, inside app screens etc.  It just checks that there's a link called "terms and conditions" on each page, that the link works, and then the test says that when it arrives on the page, it "looks like" the Ts & Cs - just enough to reassure yourself it's the right page, without "testing a constant", or "testing presentation"... so you could check that the text is correct, for example, without checking the particular font size or text layout...


问:
Explaining how the code you wrote works
I was asked to create for a freelance project a Monopoly game in Java. After finishing it the same guy asked me to create four UML diagrams from which he could understand how the game works. Everything went well this far but his third request presented me with some problems.

He now wants me to write for him in about 20-25 pages, how the game's code works, so he can understand it. I have been programming for about a year and I was never asked to do this before. I don't even know where to start to do this, from which portion of the code should I start to explain it? I basically suck at writing.

Is there any guide that could help me achive what I need? I've already created the use case diagram sequence diagram, class diagram and activity diagram.

答:
I guess that what your client asked you is the Software design document.
You can find some guides here, here and here.

A related question is https://stackoverflow.com/questions/708624/what-should-a-good-technical-design-document-contain

Title: Explaining how the code you wrote works


问:
When to use Advanced Message Queuing Protocol like RabbitMQ?
Can somebody explain me in what use-cases I should consider using AMQP like e.g. RabbitMQ? What are the pros and cons? </p>

答:
In addition to providing a buffer between a web service and another backend service, message queues can be used for more advanced scenarios. Rabbit MQ (and other mature Message Queue products also referred to as MOM -- Message Oriented Middleware) can be configured to route and distribute messages according to different rules.

For example the Pub-Sub routing technique allows a single source to send a message and have many listeners receive it. This is commonly used by stock trading software to keep the users on the floor updated.

Also because of the fact that most MOMs have sdks for multiple languages and platforms, they can be used to integrate applications that are written on different platforms.

These are just a few of the scenarios enabled by MOMs.


问:
A question on nature of generated assembly in C++ and code Algebra
I wrote this code:

```<code>#include <iostream>
int main()
{
    int a;
    std::cin >> a;
    if(a*a== 3){
        std::cout << a;
    }
    return 0;
}
</code>```

On MSVC I turned ON all optimization flags. I expected that since a*a can never be 3, so compiler should not generate code for the section:

```<code>if(a*a== 3){
    std::cout << a;
}
</code>```

However it generated code for the section. I did not check GCC or LLVM/CLang.

What are the limits of expectation from a C++ compiler in these scenarios?

答:
Compiler optimization are  normally designed to avoid repetitions, resort branches, eliminate copies on return etc. They can remove impossible branches after a static analysis (involving just constant)

But, normally, compiler don't evaluate expression containing variables since it assumes their value depends on input. Compilers cannot produce inference on values (saying "no integer can square into 3" is -at all effect- a theorem to be demonstrated, and automatic demonstration of theorems can be demonstrated to be a non-MT decidable problem: If I complicate the expression a lot, demonstrate it's "field of existence" can require ... creativity: something computer don't have by their very nature: finite state machines).

A compiler can do this kind of optimization only for a finite and pre-determined number of cases (and -frankly- I think statistics about user demands don't justify an interest in optimizing expression appositely written to fool the optimizer around - and it can always be fooled around, since whatever case it can manage you can always imagine another one it does not manage).  Attempting to solve these kind of problems in a "general way" will sooner or later find a case that will put the compiler into an infinite loop or into a stack overflow.


问:
Is it the job of programmers to design the database?
I've been a programmer for the past six years. Throughout my career, I have worked on many web applications.

Most of the time, when a database was needed, it was given to us (the programmers) or we had some legacy database to work on. If not that, we had to create and design the database on our own which was not that tough.

But are we, as programmers, supposed to create the entire database from scratch when we have to build new application where data is so important and have messy requirements with a complex data model?

Isn't it in the best interest of the app and the company to get it done by an expert?

I am not trying to run away from designing the database, but it's a thing that is so important to get right.

答:
I think the ability to design a reasonable relational database is essentially a necessity for non-junior programmers.

With that said, particularly for large applications, it's vital to get the database "right" the first time (schema, indexing, etc). If the company has access to a skilled DBA, that task should fall onto their plate; in general they will be more qualified. Potentially review/discussion should be done with the lead developer who will be accessing and working with the database on the client-side so that there are no surprises. If there's no DBA, the programmer designs the database.


问:
ASP.NET MVC vs WCF for REST API + Webpage usage
I think the discussion for programmatic service oriented usage vs human interaction is clear.

But if I were to create an application that makes use of both a programmatic API and a website that makes use of the data connected by the same API, does it lean the favour towards using only ASP.NET?

How easy is it to integrate ASP.NET and WCF to work on the same application?

答:
@tzerb has answered it correctly IMO but I wanted to extend that answer. ASP.NET Web API which is currently in beta stage and an OSS project is the closest framework that you are looking for.

The short description of the product is as follows (quoted from ASP.NET Web API page):

ASP.NET Web API is a framework that makes it easy to build HTTP
services that reach a broad range of clients, including browsers and
mobile devices. ASP.NET Web API is an ideal platform for building
RESTful applications on the .NET Framework.

As for the client application that you might be using to consume your web API, it certainly doesn't have to be an ASP.NET application. You can consume your API with a static HTML page by using JavaScript. You might get this done easily with some useful JavaScript libraries such as jQuery.

On the other hand, you can certainly consume your API on the server site in any ASP.NET application. The Web API project also introduced a new HTTP .NET client API called HttpClient which makes it easy to consume HTTP services.

In general, here are good set of resources for you to get started:

Getting Started With ASP.NET Web API - Tutorials, Videos, Samples

Remember that the project is still in its beta stage. I recommend you to follow Henrik F Nielsen blog where he posts information about latest unreleased updates to project. You can reach out the source code of the project and the development flow inside ASP.NET Web Stack project.

ContentLicense: CC BY-SA 4.0


答:
As far as writing one application that leverages both ASP.NET/MVC and WCF, its not great. WebAPI may have improved matters, but in one project I am familiar with that was using WCF and MVC in the same app, they ended up maintaining two different sets of models to represent the same concepts - one for the WCF code and one for the MVC code. You can imagine all the mappers they had to write to translate things between the two models - there were lots of lines of code there that could have / should have been avoided.

Part of why this happened is that WCF request and response objects should be annotated with [DataContract] and their properties with [DataMember], while MVC does not require this. Idiomatic MVC on the other hand is going to want ViewModels, which have different goals than WCF DataContracts. Of course, its possible that the use of two full sets of domain objects had more to do with Conway's law than WCF & MVC conflicting, but it's worth pointing out that WCF and MVC have different goals and requirements as far as output and input.

Personally, I'm partial to developing a simple but powerful services oriented back end API, particularly when you might want multiple clients. I think the advent of excellent JavaScript MVVM and micro- MVC frameworks makes this a natural choice, as writing application code using BackboneJS, KnockoutJS and others allows for a capable development environment. You can then consume the back end in the micro MVC of your choice to build your web app, or on a mobile client, and your partners might consume the same API remotely as well.

Suggestion

Either WebAPI or Service Stack might be good candidates for building your back end API.  I recommend Service Stack, as I've been using it for the last few months and have found it to be an excellent replacement to WCF. I'm currently writing a tutorial series on service stack on my blog.

The group maintaining service stack has posted an example application using the framework to develop a StackOverflow like clone which shows a development pattern that I believe is especially compelling. It involves a simple, model based services back end that you could imagine being consumed by an MVC website, a mobile app, or just about anything else easily. ServiceStack's design goals clearly encourage a pattern that should lead to less coupling between client and server. The idea is to avoid chatty API's with calls like GetCustomersInRegionWithSearchTerm(int regionId, string searchTerm) in favor of fewer methods. You might implement the same thing in service stack like this:

```<code>[Route("/customers", "GET"]
[Route("/customers/search/{SearchTerm}", "GET"]
[Route("/customers/region/{Region}", "GET"]
[Route("/customers/region/{Region}/search/{SearchTerm}", "GET"]
public class Customers
{
    public int? RegionId { get; set; }
    public string SearchTerm { get; set; }
}

public class CustomersService : Service
{
    public object Get(Customers request) {
        // handle request
        return new CustomersResponse();
    }
}
</code>```

The benefit, to my eyes, is that instead of having your business logic spread out over lots and lots of separate methods GetCustomersInRegionWithSearchTerm(int regionId, string searchTerm), GetCustomersInRegion(int regionId), GetCustomersWithSearchTerm(string searchTerm), GetCustomers(), it's all in one place. This should lead to more maintainable code.

Coincidentally, Stack Exchange hired the original Service Stack author. He continues to commit actively to the Service Stack project.

I am particularly fond of message queues for certain things - and while WCF allowed for this, WebAPI does not.  ServiceStack does allow the same web service to be invoked via MQ. For more info on this see the Redis MQ Host at: github.com/ServiceStack/ServiceStack/wiki/Messaging-and-redis

Title: ASP.NET MVC vs WCF for REST API + Webpage usage

Body:
I think the discussion for programmatic service oriented usage vs human interaction is clear.

But if I were to create an application that makes use of both a programmatic API and a website that makes use of the data connected by the same API, does it lean the favour towards using only ASP.NET?

How easy is it to integrate ASP.NET and WCF to work on the same application?

Body:
As far as writing one application that leverages both ASP.NET/MVC and WCF, its not great. WebAPI may have improved matters, but in one project I am familiar with that was using WCF and MVC in the same app, they ended up maintaining two different sets of models to represent the same concepts - one for the WCF code and one for the MVC code. You can imagine all the mappers they had to write to translate things between the two models - there were lots of lines of code there that could have / should have been avoided.

Part of why this happened is that WCF request and response objects should be annotated with [DataContract] and their properties with [DataMember], while MVC does not require this. Idiomatic MVC on the other hand is going to want ViewModels, which have different goals than WCF DataContracts. Of course, its possible that the use of two full sets of domain objects had more to do with Conway's law than WCF & MVC conflicting, but it's worth pointing out that WCF and MVC have different goals and requirements as far as output and input.

Personally, I'm partial to developing a simple but powerful services oriented back end API, particularly when you might want multiple clients. I think the advent of excellent JavaScript MVVM and micro- MVC frameworks makes this a natural choice, as writing application code using BackboneJS, KnockoutJS and others allows for a capable development environment. You can then consume the back end in the micro MVC of your choice to build your web app, or on a mobile client, and your partners might consume the same API remotely as well.

Suggestion

Either WebAPI or Service Stack might be good candidates for building your back end API.  I recommend Service Stack, as I've been using it for the last few months and have found it to be an excellent replacement to WCF. I'm currently writing a tutorial series on service stack on my blog.

The group maintaining service stack has posted an example application using the framework to develop a StackOverflow like clone which shows a development pattern that I believe is especially compelling. It involves a simple, model based services back end that you could imagine being consumed by an MVC website, a mobile app, or just about anything else easily. ServiceStack's design goals clearly encourage a pattern that should lead to less coupling between client and server. The idea is to avoid chatty API's with calls like GetCustomersInRegionWithSearchTerm(int regionId, string searchTerm) in favor of fewer methods. You might implement the same thing in service stack like this:

[Route("/customers", "GET"]
[Route("/customers/search/{SearchTerm}", "GET"]
[Route("/customers/region/{Region}", "GET"]
[Route("/customers/region/{Region}/search/{SearchTerm}", "GET"]
public class Customers
{
    public int? RegionId { get; set; }
    public string SearchTerm { get; set; }
}

public class CustomersService : Service
{
    public object Get(Customers request) {
        // handle request
        return new CustomersResponse();
    }
}

The benefit, to my eyes, is that instead of having your business logic spread out over lots and lots of separate methods GetCustomersInRegionWithSearchTerm(int regionId, string searchTerm), GetCustomersInRegion(int regionId), GetCustomersWithSearchTerm(string searchTerm), GetCustomers(), it's all in one place. This should lead to more maintainable code.

Coincidentally, Stack Exchange hired the original Service Stack author. He continues to commit actively to the Service Stack project.

I am particularly fond of message queues for certain things - and while WCF allowed for this, WebAPI does not.  ServiceStack does allow the same web service to be invoked via MQ. For more info on this see the Redis MQ Host at: github.com/ServiceStack/ServiceStack/wiki/Messaging-and-redis


答: There is research into so-called 'superoptimizing' compilers that would spot this, however not everyone is willing to wait a few hours for their code to compile.</p>

Title: A question on nature of generated assembly in C++ and code Algebra

Body:
I wrote this code:

```<code>#include <iostream>
int main()
{
    int a;
    std::cin >> a;
    if(a*a== 3){
        std::cout << a;
    }
    return 0;
}
</code>```

On MSVC I turned ON all optimization flags. I expected that since a*a can never be 3, so compiler should not generate code for the section:

```<code>if(a*a== 3){
    std::cout << a;
}
</code>```

However it generated code for the section. I did not check GCC or LLVM/CLang.

What are the limits of expectation from a C++ compiler in these scenarios?


问:
How to improve the training of students regarding maintainability?
Maintainability is a major stake of professional software development. Indeed, maintenance is nearly always the longest part of a software life cycle, as it lasts from the project release until basically the end of times.

Moreover, projects being in maintenance represent a large majority of the overall number of projects. According to http://www.vlegaci.com/298/interesting-statistics-%E2%80%93-numbers-of-programmers-in-maintenance-vs-development/, the proportion of projects being in maintenance is about 2/3.

I recently came across this question, where the guy looks pretty surprised discovering that his job is mainly about maintenance. I then decided to open a discussion (french) on the main site of the French community of software development professionals (http://www.developpez.com/). The discussion is entitled "Are students well-enough trained to the reality of professional software development?" and is mainly about maintainability. It was pointed out that, at least in France, people are not well-enough prepared to face maintenance in both aspects of it:

maintain existing code

make maintainable code

My question here echoes to this discussion and aims at finding a good way to teach maintainability.

How can we teach maintainability?

What kind of exercise would you suggest?

If you have been well-trained regarding maintainability, what particular kind of courses did you take?

[edit]
After some misunderstanding, I think I must clarify my question.
As a project leader and software developer, I often work with trainees or freshly graduated students. I once was freshly graduated myself. The thing is that students are usually unfamiliar with principles such as SOLID that increase the maintainability of a project. We often end up having important difficulties making projects evolve (low maintainability).
What I am looking for here is a concrete academical example of successful teaching about the importance of maintainability and how to make better code regarding this particular point; or possible suggestions to improve the way students are trained.

答:
I for one dislike the term Maintainable in relation to software development.  The reality is that all software is maintainable in that it can be subject to maintenance work, so the real issue is whether software is expensive or inexpensive to maintain, relatively speaking. I know this sounds like a very pedantic statement to make at the beginning of an answer, however my point will become clearer in a moment.

The problem with IT degrees which major in software development is that they really only teach students the barest minimum that the students need to know about writing software.  Professional skills and knowledge is earned through the learning that is done in the first few years after qualifying for the degree. This is when a graduate starts to work on projects that actually matter to a customer, in an environment where there is great pressure to perform, and the expectation is to create a product to a professional standard. Sadly, many companies don't encourage a culture where professional standards in software are maintained, and they end up with projects that turn out to be costly to develop and maintain as a result. Unfortunately for our graduates, they learn a lot of bad habits in such environments in the early years of their careers, and it can be a long time before they learn how to overcome these habits... if at all.

You would be better off teaching students how to write code that is clean, and how to identify the problems in software that usually end up incurring technical debt. Look into books about Clean Code, Refactoring, and Lean Software Development as a starting point as a place to start, and teach students to write unit tests before the implementation code in order to ensure there is a high degree of test coverage. Teach students to recognize duplicated and repetitive patterns within their code, and how to refactor the code to remove such duplication. Help students to understand and apply principles such as SOLID and DRY. Most importantly, do away with this idea that the ability to maintain code is something that is done based solely on the design and implementation of the code, and instead instill a sense of craftsmanship and quality in the production of software from the outset, seeking to refine the code as it is implemented in order to minimize the impact of technical debt and thereby keeping the cost of maintaining software to a minimum over time.


问:
Should I Leave off the Currency Symbol?
I'm upgrading a desktop application that currently displays the currency symbol anytime money values are displayed or printed. A friend of my from the UK told me "Whenever British people see software with the American Dollar Sign ($) it automatically turns them off."

Given the fact that we (developers) only have one shot at making a favorable first impression, wouldn't it make more sense to simply format all money values without a currency symbol?

答:
If the money values displayed are indeed dollar amounts, you should keep the $ displayed.

Not doing so makes the value ambiguous to those not in the US - they might think these are in their local currency.

If the values are indeed in local currency (whatever it may be), you should display the corresponding currency symbol (again to avoid ambiguity).

Title: Should I Leave off the Currency Symbol?


答:
Maintainability is a virtue, not a skill. There are many paths to creating maintainable projects, but no one formula that's guaranteed to produce them.

If you value virtues like kindness and generosity, you look for ways to practice the same in your daily life. It's the same with maintainability: if you and your organization value maintainability, you'll keep it in the back of your mind while designing and implementing your project. It will be a legitimate reason to spend a little extra time building something because you know that maintainability is appreciated. Conversely, spending extra time for the sake of maintainability in an organization that doesn't value it is discouraged.

If you want to teach people to make things maintainable, you should start by making it clear that your organization values maintainability. Specify it in the requirements for your projects. Make it one of the criteria for successful code reviews. In short, make maintainability part of your culture.

Next, be willing to devote some resources to improving maintainability in your existing projects. Identify those parts of a project where bugs keep cropping up, or where fixing bugs or making changes is very difficult and takes a long time, and redesign or refactor to facilitate maintenance.

Finally, indoctrinate new developers into your culture of maintainability by assigning them to teams that already practice it daily. There's no better way to help someone adopt a value than to give them plenty of good examples and guidance.

Title: How to improve the training of students regarding maintainability?

Body:
Maintainability is a major stake of professional software development. Indeed, maintenance is nearly always the longest part of a software life cycle, as it lasts from the project release until basically the end of times.

Moreover, projects being in maintenance represent a large majority of the overall number of projects. According to http://www.vlegaci.com/298/interesting-statistics-%E2%80%93-numbers-of-programmers-in-maintenance-vs-development/, the proportion of projects being in maintenance is about 2/3.

I recently came across this question, where the guy looks pretty surprised discovering that his job is mainly about maintenance. I then decided to open a discussion (french) on the main site of the French community of software development professionals (http://www.developpez.com/). The discussion is entitled "Are students well-enough trained to the reality of professional software development?" and is mainly about maintainability. It was pointed out that, at least in France, people are not well-enough prepared to face maintenance in both aspects of it:

maintain existing code

make maintainable code

My question here echoes to this discussion and aims at finding a good way to teach maintainability.

How can we teach maintainability?

What kind of exercise would you suggest?

If you have been well-trained regarding maintainability, what particular kind of courses did you take?

[edit]
After some misunderstanding, I think I must clarify my question.
As a project leader and software developer, I often work with trainees or freshly graduated students. I once was freshly graduated myself. The thing is that students are usually unfamiliar with principles such as SOLID that increase the maintainability of a project. We often end up having important difficulties making projects evolve (low maintainability).
What I am looking for here is a concrete academical example of successful teaching about the importance of maintainability and how to make better code regarding this particular point; or possible suggestions to improve the way students are trained.


问:
MVC: View-Controller Interaction
I have a Java application that I am implementing following the MVC pattern.

I want to have a window (view) that contains a form which allows the user to add several text fields. There will also be a button that will allow the user to add  more text-fields to the form.

I have several questions about this.

Will the code for adding new text-fields be considered part of the controller or the view?

If controller, then this controller will not do anything to the model, it will just modify my view, so is this a violation of MVC?

If view, then will it be a violation of MVC as the changes in view were not directed from the model?

答:
A couple of things here:

There are several ways of implementing MVC, each technology and kind
of app has it. See this great article to have a better
understanding.

An action that involves only VC is not a violation, not every user
action has to touch the three parts of MVC.

The code that will add new text-fields will be controllers, which add a view (textfield) and should add a model representing what that textfield means in your app (if the view alone has any meaning then this VC-only relationship is ok).

Changes in the view can come from two places: from the controller or from the model itself BUT by notifications (this means that the model must not know the views directly, but have a group of listeners that listens his changes).

I hope this answer plus the article clarifies a little bit more your knowledge of MVC and its implementation in your app.

Good luck!

Title: MVC: View-Controller Interaction


答:
You shouldn't be hard-coding the currency format - so you absolutely shouldn't output currency amounts formatted as $0.00 unless they are quite explicitly in a currency that use $ as its symbol (USD or otherwise).

If the currency in question is the "local" currency then you should use the currency format defined in the o/s (its available in Windows, one assumes that its also available elsewhere) unless the user explicitly chooses to use another format.

Number formats vary - especially use of "," and "." as separators so you should take that into account too

Title: Should I Leave off the Currency Symbol?

Body:
I'm upgrading a desktop application that currently displays the currency symbol anytime money values are displayed or printed. A friend of my from the UK told me "Whenever British people see software with the American Dollar Sign ($) it automatically turns them off."

Given the fact that we (developers) only have one shot at making a favorable first impression, wouldn't it make more sense to simply format all money values without a currency symbol?


答:
Establish a parameter in a configuration file or an environment variable such that at application start you read it and use its value to determine how to display the currency.

Design an application in such a way that if the parameter is not found, you show money values without a currency symbol.

we (developers) only have one shot at making a favorable first impression

Above is right, but this simple fact of life should inspire your creativity, not inhibit it.

```<code>- (developers) we show the money values as dollar sign by default,
  would you prefer it the other way?
- (customer) well, let's try it that way first
- okay - see how it works. Anything else?
- you said you can show money values the other way,
  can you show them as "USD"?
- sure, one minute. Okay - see how it works with "USD". Anything else?
- so far so good, can you show money values without a currency symbol?
- sure, one minute. Okay - see how it works that way. Anything else?
- when can I have it?
</code>```

Title: Should I Leave off the Currency Symbol?

Body:
Establish a parameter in a configuration file or an environment variable such that at application start you read it and use its value to determine how to display the currency.

Design an application in such a way that if the parameter is not found, you show money values without a currency symbol.

we (developers) only have one shot at making a favorable first impression

Above is right, but this simple fact of life should inspire your creativity, not inhibit it.

- (developers) we show the money values as dollar sign by default,
  would you prefer it the other way?
- (customer) well, let's try it that way first
- okay - see how it works. Anything else?
- you said you can show money values the other way,
  can you show them as "USD"?
- sure, one minute. Okay - see how it works with "USD". Anything else?
- so far so good, can you show money values without a currency symbol?
- sure, one minute. Okay - see how it works that way. Anything else?
- when can I have it?


答:
Currency symbol must be always present when displaying moneys.

Currency symbol should not be persisted with the amount. It should be determined at the runtime either by using culture of a thread that's being executed or by asking user to specify their culture related settings.

Just swapping one currency symbol for another isn't enough. You have to convert the amount. E.g. GBP -> USD

All this becomes more obvious when you start localising larger applications.

When I go on the site and see foreign currency, then I normally distrust the site, as my rights in their country will be very limited if something goes wrong.

Look at what others do:

http://www.amazon.com

http://www.amazon.ca

http://www.amazon.co.uk

Amazon doesn't just add currency symbol, it also adds three letter ISO code.

Title: Should I Leave off the Currency Symbol?


答:
@mattmattj: Since there a LOT of answers and the link I posted has some good pointers too I'll add something which hopefully isn't a repetition of the already posted answers.

First, one MUST define "maintainability" - there isn't a single definition accepted by all - similar to that of software architecture. So choose one that you feel is the most important, all encompassing and state it in 3-4 lines at max. Then you can talk about some metrics like - time to recollect/understand your own code (or someone else's), number of WTFs per minute/hour etc. Keep it light (humorous) - that'll make them more receptive to what you have to say after that.

Some exercises (it may sound a bit overlapping with some of the responses, please forgive that)

Split the class in two - give one section a simple coding assignment
  that needs to be done in 1-2 days. Max. Hard deadline. They have to
  get the work done under all circumstances - guideline - "working code"
  as they deem fit. For the other group of students the same assignment
  but with a list of (naming) conventions and some guidelines about
  design and how points will be deducted if not followed. This is NOT
  cheating, even if it sounds like it ;) Now have them swap the codes
  i.e. group 1 now works on what group 2 did and vice versa. Now suggest
  a modification to original coding assignment and ask them to do it in
  the same time frame. Reconvene and ask them how easy/difficult it was
  and open the floor to discussions/opinions. The point will definitely
  hit home - high chances 50% of the class would be happy and found it
  easy and 50% found it difficult. You may also ask them to work  on
  their own thing after 3 weeks and see if they can do it in 1 day ;)

(A good twist is you writing the same piece of code in a convoluted
  manner and giving to the class for modification along with their own)

Here's where you lay the foundation of maintainability - every line of code modified/updated costs the company money. The easier it is to read and recollect code the better/faster the modification that would help decrease time to market. Very important in today's fast paced technological space. Maintainability is the key to efficient evolution of systems.

It's important to understand the difference between greenfield and brownfield development - not every project or system would be created from scratch (it's rather hard to find or be part of "from scratch" projects). Explaining that the field is "inherently" brown and you must spend time shaping it as you go along with eventual phase out when it grows "out of hand" (only possible when the drift is too much and 'unmaintainable'). The sooner they accept that the better. This is difficult since programming is inherently creative but enhancing someone else's code isn't perceived as such - twist it around. Creativity there is the ability to understand the code and then apply "your" creativity to enhance it - if better maintained you'll be able to more creatively enhance it in the future.

Feel free to refer to the spaghetti analogy in the above link...hope this helps hit some points home. The other answers help fill in the gaps and should help you with the teaching! Best of luck!


问:
What advantages does developing applications for smartphones have over developing the same application as a web application?
Let's take the Facebook application as an example. Why did they develop an application when the users could just access to their page and do the same? For me that represents more maintenance and more cost because for each feature added to the web application that feature will have to be added to the smartphone application as well.

So why would I want to develop more than once (for each patform iOS, Android, etc) when I could just have one web application? What benefits do I get? The only one that comes to my mind is GPS feature.

EDIT:

My question is more oriented towards business applications that are going to be used only by some members of the company, it's not about selling the application (private use). So contrary to what some answers say about that by developing as a smartphone application it will benefit from more sells because of the "smartphone stores" for me this point is not important because the application is for private use.

By developing the application as a web application it means that it can be accessed through smartphone browser and also in a PC (any capable browser), but developing as a native application would limit this to only some kind of smartphone so we would be limiting  the use.  On the other hand developing it as a web application means that in order to access the application an Internet connection must be available.

So keeping this in mind how would you convince your boss to write the application for a given smartphone platform (iOS/Android) vs developing it as a web application?

答:
Web apps are the way I'd recommend going. There are frameworks that can help a lot, like  jQuery Mobile. Plus, many of the features others are describing here are available to a web app. Familiarize yourself with a few of these "HTML5" specs:

Geolocation API (GPS)

Offline Web Applications

Web Workers

Server Sent Events (Push Notification)

More and more features are being made available through JavaScript on more recent mobile browsers, so I've found the reasons for a native app to be less and less compelling.

The main reason I can still think you'd want to make a native app is that it's possibly easier to monetize it through the various platforms' app stores.


问:
Where are the next-next-generation editors?
I was reading an old Coding Horror article about indentation, when I read this:

Or, maybe you're using a next-next-generation editor that treats code as "data" and the layout (including whitespace) as a "view", making all these concerns largely irrelevant.

Exactly what next-next-generation editors was Jeff Atwood referring to?

答:
The editors Jeff Atwood is talking are editors we may expect to have in future. I believe he hadn't any existent one in mind, but maybe I'm wrong.

This being said, the tabs vs. spaces issue he's talking about is largely solved by some today's IDEs. Visual Studio, for example:

Adjusts spaces for you, making it easy to keep the same formatting in your code and never care about spaces. For example if you start typing:

```<code>     if  (! this.isDead )
 {
this.Kill  ( ) ;
    }
</code>```

it will fix it for you while you type:

```<code>if (!this.isDead)
{
    this.Kill();
}
</code>```

Let you to reformat the document¹ with Ctrl+E → Ctrl+F (or Ctrl+Shift+F in Eclipse), if you still succeeded in messing up with spaces.

Enforces either  tabs or  spaces rule: if you open a document which contain both spaces and tabs, you will be asked if you want to transform tabs to spaces or spaces to tabs or keep everything as is.

Adjusts the indentation according to your settings, which makes it irrelevant to discuss the number of spaces per indentation (four vs. two for example) inside a team.

Another point is that today's IDEs are powerful enough to provide better visualization of code, making whitespace/tabs/indentation discussions less relevant in some circumstances. Instead of visualizing code as code, i.e. in plain text, you can view and manipulate² diagrams, graphs, etc. Visual Studio, for example:

Provide designers for a lot of stuff. You may for example create a Windows Form just through drag and drop, and never care about how the code is written and what indentation is used. Drag and drop development is also strongly encouraged in general by Microsoft and they are working hard on providing different means of creating code without writing it manually. Aside personal opinions (mine being particularly negative³), this drag and drop paradigm let you imagine what would be the next-next-generation editors and how they will abstract the tabs/spaces/indentation discussions⁴.

Let you create the basic structure with fully documented classes, interfaces, properties, empty (not implemented) methods, etc. by using class diagrams, without ever opening the source code itself. You must still go to code to actually write the bodies of methods or properties, but still, a lot of work can be done through class diagrams⁵.

Let generate code from UML⁶.

To conclude, with today IDEs, you don't even need to see the source code in some cases, since you may use alternative ways of viewing code. In this case, you don't have to care about indentation. And when you have to get back to the plain text source code, the IDE is clever enough to properly format the code as you write.

¹ At least for C#. JavaScript auto-format support is pretty poor.

² The manipulation part is particularly important. If you can just view the code as data, but not change it, you still have all the issues related to whitespace, tabs and indentation. Older IDEs started to provide alternative means to visualize code, but it's only recently that it became popular to have a two ways relationship between a diagram (or other form of visualization) and the source code itself.

³ Mostly because auto-generated code is always too dirty, and is too limited in capabilities. For example, for the last ten years, each new WYSIWYG promised clean HTML and CSS, and still when you need clean code with CSS sprites and other advanced features, you will need to do the work by hand.

⁴ The code created by Windows Forms designer may not comply to StyleCop rules, but still, I never had to fix indentation for the auto-generated Windows Forms code.

⁵ The generated code violates magnificently lots of StyleCop rules, which means that the usefulness of class diagrams to generate code is rather limited if you care about style. Still, it takes away from you the care about whitespace, tabs and indentation.

⁶ I never tested this feature, because I don't have TFS. From what I remember, you can actually generate source code from some diagrams with VS2010 Ultimate + TFS. If I am wrong, feel free to edit my answer or adding a comment.

Body:
The editors Jeff Atwood is talking are editors we may expect to have in future. I believe he hadn't any existent one in mind, but maybe I'm wrong.

This being said, the tabs vs. spaces issue he's talking about is largely solved by some today's IDEs. Visual Studio, for example:

Adjusts spaces for you, making it easy to keep the same formatting in your code and never care about spaces. For example if you start typing:

     if  (! this.isDead )
 {
this.Kill  ( ) ;
    }

it will fix it for you while you type:

if (!this.isDead)
{
    this.Kill();
}

Let you to reformat the document¹ with Ctrl+E → Ctrl+F (or Ctrl+Shift+F in Eclipse), if you still succeeded in messing up with spaces.

Enforces either  tabs or  spaces rule: if you open a document which contain both spaces and tabs, you will be asked if you want to transform tabs to spaces or spaces to tabs or keep everything as is.

Adjusts the indentation according to your settings, which makes it irrelevant to discuss the number of spaces per indentation (four vs. two for example) inside a team.

Another point is that today's IDEs are powerful enough to provide better visualization of code, making whitespace/tabs/indentation discussions less relevant in some circumstances. Instead of visualizing code as code, i.e. in plain text, you can view and manipulate² diagrams, graphs, etc. Visual Studio, for example:

Provide designers for a lot of stuff. You may for example create a Windows Form just through drag and drop, and never care about how the code is written and what indentation is used. Drag and drop development is also strongly encouraged in general by Microsoft and they are working hard on providing different means of creating code without writing it manually. Aside personal opinions (mine being particularly negative³), this drag and drop paradigm let you imagine what would be the next-next-generation editors and how they will abstract the tabs/spaces/indentation discussions⁴.

Let you create the basic structure with fully documented classes, interfaces, properties, empty (not implemented) methods, etc. by using class diagrams, without ever opening the source code itself. You must still go to code to actually write the bodies of methods or properties, but still, a lot of work can be done through class diagrams⁵.

Let generate code from UML⁶.

To conclude, with today IDEs, you don't even need to see the source code in some cases, since you may use alternative ways of viewing code. In this case, you don't have to care about indentation. And when you have to get back to the plain text source code, the IDE is clever enough to properly format the code as you write.

¹ At least for C#. JavaScript auto-format support is pretty poor.

² The manipulation part is particularly important. If you can just view the code as data, but not change it, you still have all the issues related to whitespace, tabs and indentation. Older IDEs started to provide alternative means to visualize code, but it's only recently that it became popular to have a two ways relationship between a diagram (or other form of visualization) and the source code itself.

³ Mostly because auto-generated code is always too dirty, and is too limited in capabilities. For example, for the last ten years, each new WYSIWYG promised clean HTML and CSS, and still when you need clean code with CSS sprites and other advanced features, you will need to do the work by hand.

⁴ The code created by Windows Forms designer may not comply to StyleCop rules, but still, I never had to fix indentation for the auto-generated Windows Forms code.

⁵ The generated code violates magnificently lots of StyleCop rules, which means that the usefulness of class diagrams to generate code is rather limited if you care about style. Still, it takes away from you the care about whitespace, tabs and indentation.

⁶ I never tested this feature, because I don't have TFS. From what I remember, you can actually generate source code from some diagrams with VS2010 Ultimate + TFS. If I am wrong, feel free to edit my answer or adding a comment.


问:
Sequence diagram should consist of View objects, DB objects, etc.?
What is the correct usage of UML sequence diagrams? Should they contain objects of View classes or DB classes? Or should they modeled in a more generalized fashion? Or is this completely arbitrary?</p>

答:
It should contain the objects of interest in the interaction.

Like any type of documentation, it should focus on what you are trying to document. If you are documenting the DB interaction, you should have the DB classes involved. If not, you shouldn't.


问:
Is there really Object-relational impedance mismatch?
It is always stated that it is hard to store applications objects in relational databases - the object-relational impedance mismatch - and that is why Document databases are better.

However, is there really an impedance mismatch? And object has a key (albeit it may be hidden away by the runtime as a pointer to memory), a set of values, and foreign keys to other objects. Objects are as much made up of tables as it is a document. Neither really fit.

I can see a use for databases to model the data into specific shapes for scenarios in the application - e.g. to speed up database lookup and avoid joins, etc., but won't it be better to keep the data as normalized as possible at the core, and transform as required?

答:
There is definitely object-relational impedance.  I had to deal with this for years on a product that kept its data on a database but was OO when it ran.

As a vastly simplified example, consider three DB tables.  Two are just lists, one containing people and one containing jobs.  The third is a link between people and jobs, with a column for each.  (And all three have lots of columns for lots of subsidiary data.)

In the UI, a user wants to look at the data in terms of a job and the people working on it.  A look at the DB, if it's large, is going to be worthless--too much disorganized info.  But in the UI, a job object can serve as the basis for good display.  Even if the user has a list of a million jobs, he can scroll to the one he wants and see all the relevant info:  who's working on it and when and how hard and with what skills, etc.

So on the DB you have 3 tables.  In the OO program, you have job objects, people objects and the links between them.  The jobs and people lists relate directly to the DB tables, but there is no list of links.  The links are part of, or at any rate tied to, the job objects.  To create a link table from the OO data, you have to work through all the jobs.  To create a proper jobs object, you have to read through the link table and do some awkward rearranging of data.

This is the essence of the impedance.  This example is simple in order to be easily understood, but it drastically understates the real-world difficulty in translating between the two concepts.

OO is much faster.  It's easier to use once it has been set up.  However, it forces a certain organization on the data.  If this organization is not done right, or is not adequate, there can be trouble.  For instance, in my example the key object is the job.  If you want to know what work an individual is doing, it's no good.  In this simple example, it is obvious that there needs to be a people object that contains all the work a person is doing, but in a real system the number of possible structures will approach infinity; you have to choose to do that limited number that will let the program do its job.

OO bogs when the random-access aspect of memory becomes slow.  OO depends on a lot of direct links between bits of data.  How is a large OO database supposed to work?  A Document Database makes more sense, but it will either have to really be an OO DB or duplicate vast quantities of data:  note that a job object includes people objects, and those people objects include the job object.

Relational data is much slower, but it is without prejudices.  A bit of SQL and you can look at the data any way you want.  The other, overwhelming, advantage it has is that slow, not-so-random memory--which will bring OO to a halt--doesn't bother it.  So if you have terrabytes of data, you want your data stored relationally, not object-orientedly.

So I think we're stuck with relational databases and object-oriented programs and doing a lot of gyrations to get data from the one to the other and back again.

Also:  I have recently done some work on a system that uses in-memory relational data.  It is very slow, but not so slow as to be seriously annoying (it's not a computer game!) and the original developers, while they had to design a DB, got to skip worrying about an OO design.  I considered OO'ing a bit of it, but that meant a lot of programming versus writing just a bit of fancy SQL (LINQ, actually).  It clued me in that relational could sometimes compete with OO on its own turf.

It also points out that OO forces organization on the data.  If the original developers had known what I needed to do and used OO to do it, the program would have run faster and I could have modified it with a lot less effort.  (SQL is tricky.)  But if they hadn't OO'ed it they way I needed it done, I'd have been right where I was but without the in-memory relational DB.

Summary:  OO and relational are two different things, and converting between them involves impedance--it's a pain.  Each has its uses, and I think we're often going to be stuck using both.


答:
Yes, there is Object-relational impedance. In the early 1980s and 1990s they thought that the solution would be object databases, the most famous of wich is probably the Zope Object Database. Now it is tackled mostry with Object-relational mapping software.

The existance of all these products proves that there are many problems to solve to make the relational world communicate with the object oriented one.

Title: Is there really Object-relational impedance mismatch?

Body:
It is always stated that it is hard to store applications objects in relational databases - the object-relational impedance mismatch - and that is why Document databases are better.

However, is there really an impedance mismatch? And object has a key (albeit it may be hidden away by the runtime as a pointer to memory), a set of values, and foreign keys to other objects. Objects are as much made up of tables as it is a document. Neither really fit.

I can see a use for databases to model the data into specific shapes for scenarios in the application - e.g. to speed up database lookup and avoid joins, etc., but won't it be better to keep the data as normalized as possible at the core, and transform as required?


答: Jeff was probably refering to projectional editors that actually work on the abstract syntax but only visualize text, graphics or other editable representations of the data. Jetbrains MPS or the Concrete Editor are such tools. The induced represenation of the data is actually a pro and a con since the data itself is likely to be persisted in a binary format thus is cannot be edited with traditional tools like plain text editors.</p>

Title: Where are the next-next-generation editors?

Body:
I was reading an old Coding Horror article about indentation, when I read this:

Or, maybe you're using a next-next-generation editor that treats code as "data" and the layout (including whitespace) as a "view", making all these concerns largely irrelevant.

Exactly what next-next-generation editors was Jeff Atwood referring to?


答:
I use the term 'Virtual Formatting' to describe the behaviour when code is formatted as you type or drag-and-drop, text is rendered using dynamic margins without the aid of any tab or space characters. Code simply re-flows into a new formatting shape automatically as the context changes. Special provision is made to ensure code doesn't move around too much whilst you're still typing though, as this can be a distraction.

If you're interested in virtual formatting, there's a video here that shows the behaviour of a freeware XML editor that I distribute as a proof of concept that also happens to do something vaguely useful.


答:
I see two questions here:

Should database developers model business logic?

Should I know how to persist data to the database?

Business Logic

Business logic does not live in a database. It's a conceptual model which must be independent of other layers within your system.

You can always replace one database with another, or you might even decide to use a NoSQL solutions to address potential performance issues.

Database developers can be involved during modelling process, but normally this is done by people with a complete understanding of a problem domain. In our organisation this is done by server side developers.

Many think that database is a foundation of your application. Make poor foundation, and the system will fall. I disagree with this. I see database as a storage medium that can be always replaced.

Persisting Data

You should know how to persist data to different storage mediums, including SQL and NoSQL solutions.

Level of required expertise will vary with the size of the system that you are working on.

Small companies would expect you to have that knowledge, when larger companies would normally hire experts to address performance, scalability and security related requirements.

To summarise:

Domain model is a foundation of your system, not the database.

If you work for a small company on a relatively small project, then you should probably design the database yourself.

If you work for a large company on an enterprise system, then it probably makes more sense to pass work to the domain experts.

Title: Is it the job of programmers to design the database?

Body:
I've been a programmer for the past six years. Throughout my career, I have worked on many web applications.

Most of the time, when a database was needed, it was given to us (the programmers) or we had some legacy database to work on. If not that, we had to create and design the database on our own which was not that tough.

But are we, as programmers, supposed to create the entire database from scratch when we have to build new application where data is so important and have messy requirements with a complex data model?

Isn't it in the best interest of the app and the company to get it done by an expert?

I am not trying to run away from designing the database, but it's a thing that is so important to get right.


答:
Modifying the page by adding extra fields has nothing to do with MVC.

You will be adding elements to the DOM with jQuery/JavaScript. This is simple presentation logic and it'll be a part of your view.

Title: MVC: View-Controller Interaction

Body:
I have a Java application that I am implementing following the MVC pattern.

I want to have a window (view) that contains a form which allows the user to add several text fields. There will also be a button that will allow the user to add  more text-fields to the form.

I have several questions about this.

Will the code for adding new text-fields be considered part of the controller or the view?

If controller, then this controller will not do anything to the model, it will just modify my view, so is this a violation of MVC?

If view, then will it be a violation of MVC as the changes in view were not directed from the model?


答:
Diagrams that you have created would verify the business logic, but this is something that they already know, so I would question a need for these diagrams.

If they are paying for your time and you feel that you can explain your work in 25 pages, then do it.

You could ask them to debug code and make a list of questions for you.

You could also spend a day with them explaining what you have done.

Title: Explaining how the code you wrote works

Body:
I was asked to create for a freelance project a Monopoly game in Java. After finishing it the same guy asked me to create four UML diagrams from which he could understand how the game works. Everything went well this far but his third request presented me with some problems.

He now wants me to write for him in about 20-25 pages, how the game's code works, so he can understand it. I have been programming for about a year and I was never asked to do this before. I don't even know where to start to do this, from which portion of the code should I start to explain it? I basically suck at writing.

Is there any guide that could help me achive what I need? I've already created the use case diagram sequence diagram, class diagram and activity diagram.


问:
Recommendations for teaching junior programmers good coding style
I am a big fan of good coding style, producing clean, clear code that runs well and is easy to use and integrate into larger systems. I believe that we programmers are essentially craftspeople who should take pride in our work, every line. I am not fond of code that is inconsistently formatted, cluttered with commented out experimental code, and rife with unhelpful or misleading function and variable names. But I sometimes find it hard to argue with code like this that basically works.

If you think that coding style matters, I am looking for recommendations for ways of teaching good, professional coding style to the junior programmers under me. I want them to take pride in their work, but my concern is that they appear to become satisfied when their code just barely works, and seem to have no interest in producing what professionals like me would consider professional code. On the other hand, if you think coding style is not particularly valuable, I welcome your comments and am open to reconsidering my standards and tolerances.

I know the usual arguments in favor of good code: comprehensibility, ease of maintenance, etc., but I would also like to hear some rebuttals to arguments like "it works, what more do you want?"

In our industry we can use the compiler to hide a multitude of sins. Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

[While there are several existing questions on coding style, I didn't find any that related to teaching methods and ways to instill good coding style in junior programmers.]

答:
I think an underestimated aspect of coding style is that it manifests itself naturally. When I see a source code I've written a long time ago, I usually feel a compelling wish to break through time-space continuum just to punch myself in the face for the (perceived) monstrosities I've performed in the said source. Since you are mentoring juniors, and they tend to learn fast (since they need to), do the simplest possible solution: allow them to write a bad piece of code (once!), then make them maintain it. Chances are, if they're good at software engineering, they'll repent their sins and refactor the code properly. Of course, don't release their spaghetti collection as production-grade code, I'm certain there are a lot of opportunities to make a junior dev write something small, almost 'throwaway'.

There's no software school like real life

DRY makes perfect sense when you've had to edit that copy-pasted line 4 times, and you did it only 3, that's why the code dereferences a null pointer and the app crashes...

Also, the energy you will spend trying to convey 'good' methodologies upon them will probably be a lot, and it's not certain they won't dismiss it with a "Whatever, it works" as you pointed out.

So show them in practice that code style matters, by demonstrating its better readability to themselves, too.

Supporting software is way more useful for programmers than they think it is

I think it's another topic, but most people instinctively assume they write good code (I plead guilty). So fixing someone else's mess can be good for one's habits - you wouldn't sin if you just returned from a vacation in hell, right (religious views aside)?


问:
Paid open-source app
The question that bothers me is whether it is possible/feasible/reasonable to expect for an open-source app to sell well on the mobile market?

Should I believe that my users will use my app, rather than build the checked-out version, and, more important, how can I deal with the competition if I make my app available under an OSS license?

So far the only link on the subject I've found is http://blog.zachwaugh.com/post/17554643060/selling-open-source-apps however it deals with a Mac OS X app.

I should mention my question does not focus on iOS, Android or another OS, it's about mobile applications in general.

EDIT: The very reasonable question of whether my users are programmers has been asked.

I do not expect most of my users to be even remotely familiar with programming.

答:
Is the community going to contribute to the source code?  If not, there's no need to make it publicly available.

You could give paying customers the source as an added bonus so they can modify the app to fit their needs.

Write your own license that suites your needs like a glove. Let your needs and wants guide the license, not the other way around.

Title: Paid open-source app


问:
How can a PHP programmer best prepare for a C++ course?
I have never programmed in C++, but am going to be taking a class that involves programming in C++ in January. I want to be able to excel in the class, and looking for advice, as I come from a PHP background. How can I best prepare myself for success?</p>

答: That's a good topic. But I keep wondering why other programmers feel offended anytime the issue of PHP comes up? Looking around the web, PHP is clearly the winner - l don't even know the importance of all these other languages, when almost 70% of the web is in the hand of PHP. You don't need to abandon your PHP background, a good programmer be it in PHP, Java or any other language can pick up any other language easily, just study the syntax and you are good to go. As a PHP programmer, it never took me long to start piloting java, but not much use.Rick Rhodes, l like your answer.</p>


问:
How to verify the client's view is consistent with the remote model?
i'm designing a client-server system via web broswser and i have this problem:
I send the data to the client via JSON, then the javascript view shows the stuff. Then the user takes actions and commands are sent back to the server. Usual stuff, the problem is what if the view's data is corrupted or old?
One solution i thought is making a hash via SHA1 or some other algorithm of the full objects in the client's model, but JSON data is not ordered, also this adds delays to the system.
How do google docs manages this kind of thing?
Also, sending ALL THE DATA, every time the model is updated doesn't make sense, but how do i keep consistency by only sending changes?
I think the whole problem is just one.</p>

答:
In most cases, I would probably do it like this:

Store an initial state plus all changes made since that state (all timestamped).

Poll only for changes since the last timestamp retrieved.

If someone posts an update, send the last-seen timestamp with it. If there have been updates since then, deal with that accordingly. (See below)

Periodically, calculate the state of the data at a given time.

When you load the state fresh, only load the last-calculated state plus changes made since that.

When I say "deal with that accordingly," I mean that it very much depends on the case. If I can safely make the second update and send the missing update back to the client, I will do. But sometimes you will want to inform the user of a double update and allow them to make the decision what to do next.


答:
Your mobile application being open source will not have much of an impact on the sales of the app if it is on the market.

There is a lot of work involved in doing a checkout (you need the relevant SCM installed) and getting the appropriate SDK set up (the relevant license acquired if it is iOS or Windows). That is provided that your target users are that knowledgeable to know that this is what they need to do to get it for free.

It is actually a positive upto a certain level. Providing source may actually be a bonus and would tilt many a advanced user to your side. These users can extend or build apps alongside your application that uses your application features like Activities in android.

Making the source available is not by itself going to attract contributors. The app needs to attract sufficient attraction before that happens.

If you're concerned about competition, then it's best to not open source at all. It is very hard to establish that your featuers were copied and time consuming to get that issue settled.

Title: Paid open-source app

Body:
The question that bothers me is whether it is possible/feasible/reasonable to expect for an open-source app to sell well on the mobile market?

Should I believe that my users will use my app, rather than build the checked-out version, and, more important, how can I deal with the competition if I make my app available under an OSS license?

So far the only link on the subject I've found is http://blog.zachwaugh.com/post/17554643060/selling-open-source-apps however it deals with a Mac OS X app.

I should mention my question does not focus on iOS, Android or another OS, it's about mobile applications in general.

EDIT: The very reasonable question of whether my users are programmers has been asked.

I do not expect most of my users to be even remotely familiar with programming.


答:
For starters, the vast majority of apps, of the million out there, do not sell well, whether open or closed source.  So don't expect any app to sell well unless it is a stand-out app and well marketed.

For iOS apps, someone would need to have paid Apple $99/annum for an iOS Developer program enrollment, plus have a Mac, in order to be able to download your open source, build the app, and load it on their device, without buying your app.  Not many end users would do this, even if they had the expertise.

However, there is little or nothing to prevent some other developers from doing this, even submitting it to an app store under their own name, perhaps undercutting your price, or adding advertisements to a free app.

There are more and more developers doing the latter.  Some reportedly even using content that is copyrighted and not open source.  So competition is almost guaranteed if your app gains any visibility.  Your advantage over the copycats, if any, will be brand name recognition from marketing, PR, or fame, if you have any, as many of the app stores do attempt to protect registered trademarks.

ADDED:

If you distribute your open source under the GPL v3 license, there may be some legal opinion that using code so licensed is incompatible with Apple's iOS App store DRM.  But you, as the 100% copyright holder, could submit your own app to the iOS App store yourself, since the license doesn't apply to the owner.  However, you may be able to consult an attorney about whether you would have grounds to sue anyone else who took your code under GPL v3 license, and tried to do likewise.  This might cost you money to enforce though.  But IANAL, so consult a lawyer if you want to think about using this strategy.

ADDED later:

As of Xcode 7.x, one no longer needs to pay Apple a $99/annum developer enrollment fee to install apps from a Mac to their own connected iOS devices.  Only a valid Apple Developer ID and knowledge in how to use Xcode is needed.

Title: Paid open-source app


问:
Understanding already existing complex code base

Possible Duplicate:

  What is the most effective way to add functionality to unfamiliar, structurally unsound code?

Till now, all I have worked on is with Java projects that I build from scratch (mostly course projects and some hobby stuff). But now, I have come across a huge code base of about 46000 lines spread across around 200 classes. Additionally there are around 10 dependent libraries.

The problem is not only that I have never worked with someone else's code before, but I have not worked with such a huge code-base before too.

I am asked to completely understand the code-base and suggest improvements to the existing design. Now, I am kind of stuck. I start with some part of the code and then by the time I reach some other part of the code, I have lost the working details of the previous part.

I could really use your suggestions and experiences to deal with this issue. How do I proceed/document the details of the classes to understand the code better?

Edit:
This is a university level research project. Students have developed it over couple of years and the bad part: The students who wrote this have already graduated. The existing documentation (only in the form of Javadocs, not UML stuff) is a lot but not helpful in terms of understanding the application design.

答:
Working with the code is the best way to learn it. There is no "express" way to learn a huge code base,  but there are a few things you can do.

You can try modifying the code to add small features and to refactor and learn the code base in that way. Try focusing on small, localized sections of the code base, trying to learn it in little pieces.

If there are unit tests, you can try studying them to get a better insight into how the code is meant to work. If there aren't tests, writing them can be a fantastic way to understand parts of the code. By definition, unit tests are supposed to only test one unit, so you can focus on just that unit, mocking away any other dependencies. This will let you focus and learn one unit of code at a time, until you know more and more of the code base.

Another great technique is running the code in a debugger and stepping through the whole execution of some use case. This will give you a good view of how the system responds and executes some feature.

Don't expect this to happen overnight. It'll take some time to understand the intricacies of the code base, but writing/understanding unit tests is a fantastic way to learn them.


问:
What's the difference between dictionary word "Scheme" and Computer term "Schema"
What's the difference?

In my opinion, I can replace the term "Schema" with "Scheme". Can I?

答:
Although Dan's link to the English SE does provide some context to the words, I don't think it really gets across how the two are different in the lexicons of most programmers.

I don't have a technical source for you, but the general difference is that Schema is something formal, a model typically.  See, for example, an XML Schema, meaning a document describing the proper elements and structure of an XML document. Schema also very commonly refers to a database's design and layout of tables and fields.  From these data-descriptive uses, some people refer to any kind of diagram of a system or process as a "schema".  Still, I think the word most specifically refers to a model you can verify an implementation against.

"Scheme" is rarely used in programming, except to refer to the sub-genus of LISP languages called Schemes (Racket, formally PLT, being perhaps the best known implementation of the Scheme language standard).  I have also occasionally heard the word used to mean "a plan or methodology" as well, as in "what's your scheme for solving this database issue?"  No other formal usage comes to mind.


问:
Display rich text in tool tip
In this particular website, when you hover your mouse over a particular region, it displays something that is clickable. I know of tool tips, but in my experience, I have only used tool tips to show static text, not click able html text.
http://www.cry.org/projects/projects.html

What technology do you think is being used here? Also, is this a tool tip?

答:
These aren't tooltips like those created with a title attribute in HTML. This is normally called a "rich tooltip" and is done using an absolutely or relatively positioned HTML element with an appropriate z-index if required, so full HTML markup can be used. While it could be done with CSS alone in modern browsers, Javascript is most often used to show and hide the element, sometimes with a fade effect.

Many Javascript UI libraries implement similar functionality, see e.g. this JQuery UI demo, dijit.Tooltip, etc.

Title: Display rich text in tool tip


答:
Often we don't pay/donate because we are lazy and even want to but postpone indefinitely

An example if you don't mind. It's not about mobile, but the concept is interesting. It's ssh server for Windows, called KpyM. The app is open-sourced and the download version contained 5-seconds delay for any client connection if not registered. This practice is usual for closed sharewares, but this was the first time I met it in OSS. And finally I paid. Because

I could live with this reminder, but it reminded me that the job is done and it's better for it to be rewarded. The more I feel the program worked as expected, the more this delay was about wish to pay (because if it's irritation, I can always modify the sources and recompile)

I could recompile without the delay, but I had strong urge not to do. Not mentioning recompiling it and upload this version somewhere for ethical reasons. Hacking closed binaries is illegal, but sometimes has reasoning (for example, solving a complex task), but changing the source code of an OSS program in similar cases won't even get you a badge of a smart guy :)

Title: Paid open-source app


答:
Unless something like this exists in documentation, I like to draw UML class and sequence diagrams to get a feel for static structure and dynamic behaviour of the code. These diagrams do not have to be formally correct, but give me something to look at when I'm having a "what is this doing again??" moment.

If they are already there, I also like to look at unit tests to see how it all comes together. If there aren't any, writing them is also a good way to get into the code base.

EDIT: I don't draw the diagrams for all the code, only the part that I'm currently working on and that confuses me (complex inheritance hierarchies etc).

Title: Understanding already existing complex code base

Body:
Possible Duplicate:

  What is the most effective way to add functionality to unfamiliar, structurally unsound code?

Till now, all I have worked on is with Java projects that I build from scratch (mostly course projects and some hobby stuff). But now, I have come across a huge code base of about 46000 lines spread across around 200 classes. Additionally there are around 10 dependent libraries.

The problem is not only that I have never worked with someone else's code before, but I have not worked with such a huge code-base before too.

I am asked to completely understand the code-base and suggest improvements to the existing design. Now, I am kind of stuck. I start with some part of the code and then by the time I reach some other part of the code, I have lost the working details of the previous part.

I could really use your suggestions and experiences to deal with this issue. How do I proceed/document the details of the classes to understand the code better?

Edit:
This is a university level research project. Students have developed it over couple of years and the bad part: The students who wrote this have already graduated. The existing documentation (only in the form of Javadocs, not UML stuff) is a lot but not helpful in terms of understanding the application design.


答:
I have to do lot of code reviews and it includes larges and complex code base.

I try to build a mind map of the component when it's possible.

If I have to work or contribute on the project, something very effective I do is adding (or changing) comments in area that were not clear at the first place.

Finally, a simple "architecture" overview of the project must be build for future code reviewers. The mind map will be very helpful for this step.


答:
I was in a similar position after I finished first year at university. Based on that experience I think that you bit more than you can chew on.

The following might make your life easier, but you'll need to put in a lot of work.

Gain complete understanding of your problem domain. Talk to the business and model application's features with use case diagrams or something similar. I assume you have unlimited time and resources to do that.

You need to break down your problem into smaller tasks. Set yourself a goal and work towards the goal. E.g. I want to understand authentication process. Find the code that you think does that and start working through that. If you'll get hang up on entire system, you will be very unlikely to get anywhere in my opinion.

Get contacts of people who have worked on this previously. If they are still in the same company, then work with them after you get familiarised with the system.

Going through code, documenting what it does will take you a very long time. I doubt that you can afford that.

Deploy system in a fresh environment. Hopefully it'l break and you'll have to debug lots of code to see what's happening.

Assuming you have the use cases, start to debug through the codebase.

Make sure you are clear on why business wants you to review the codebase. Surely it's not just an expensive and pointless exercise, so they must have a good reason. This should give you a good idea where to look.

There are tools that analyse codebase and tell you whether it's tightly coupled and how much duplicate code is there. This might be useful, but not at the start of your project.

Check whether there are any unit tests. Start running those to see what the system is capable of doing.

Things to keep in mind:

It's not an easy task, so don't beat up yourself.

There will be a lot you won't understand, so don't hang up on those things and keep moving forward.

This is normally quite de-motivational, therefore it's important you take a note of your progress. I normally have this on a whiteboard in front of me.

Don't hang up on big numbers. Yes, you can use that in self-defence and 200 classes probably equals to quite a few responsibilities, but this doesn't make your life any easier, so lets look for solutions :)


问:
When is it acceptable to NOT fix broken windows?
In reference to broken windows, are there times when refactoring is best left for a future activity?

For example, if a project to add some new features to an existing internal system is assigned to a team that has not worked with the system until now, and is given a short timeline in which to work with - can it be ever be justifiable to defer major refactorings to existing code for the sake of making the deadline in this scenario?

答:
can it be ever be justifiable to defer major refactorings to existing
  code for the sake of making the deadline in this scenario?

If something is broken, then most likely not. You won't drive a car with partially-working brakes, would you? (Unless the risk of not getting somewhere on time is greater than the risk of crashing because of the faulty brakes.) Far from ideal solution, but unfortunately it happens.

However, if you are talking about re-factoring working code, then I'd consider the following:

If it was up to our senior developers or technical director than we would never release any software. We'd always re-factor and strive for perfectionism.

If re-factoring will have a negative impact on profitability of business then it should be re-scheduled.

If your business have promised to deliver certain functionality by a given date, then you would refactor later. Think about Red Nose Day charity - every year they can gather donations for a period of 24 or 48 hours. There is no way that they would re-factor their codebase if they thought it might stop them from taking donations in that time gap. Additionally, if there is a broken window, but it won't affect their ability to take donations, then it's quite likely that they will choose not to re-factor.

You will always find a better way to do something. It's a natural process and it's very important to be able to draw a line.


问:
Is there any algorithm book that teaches like Head First series?
As a Java programmer I need to learn algorithms (for programming Challenges). I read some Head First Series (JAVA owned by me) and they are pretty brain friendly. So I was wondering is there any algorithm book that will be simple to understand and also goes to the crux of each algo.</p>

答:
I found this

http://www.amazon.co.uk/Data-Structures-Algorithms-Michael-Goodrich/dp/0471738840/ref=sr_1_3?ie=UTF8&qid=1335693080&sr=8-3

to be very helpful during my second year at the university.


答:
Focus on data structures -- that is where the rubber hits the road.

Data definition (e.g. database schema, file formats) takes far less lines (of code) than application logic, but is crucial for really understanding what application is doing.  Learn the data structures and relations. After that it's far more easier to wrap your head around rest of the program.

Knowing the data layout gives you sense of direction while reading code. It's like having map and compass while navigating in forest.

"Show me your flowchart and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won't usually need your flowchart; it'll be obvious." -- Fred Brooks, The Mythical Man-Month

PS. Data lives forever. Programs (and computers) are transitory.


答: Related to this. But with the addition of a Lines of code component. And by the way, 46000 lines of code is a medium sized application in my experience.


问:
Adding scripting capability to a .NET application
I already have a working implementation that adds scripting to an application. The application currently generates and compiles scripts from C# snippets (taken from different user provides configuration files) into assemblies using the CodeDOM. As it sounded like a good idea at first I ran into following issues:

difficult AppDomain handling and need for Serialization

performance issue => frequent script changes trigger a recompilation

changes cannot be made in-place in the scripts while running

difficult to provide a GUI for debugging (breakpoints), the script writer actually needs a debugger...

I "hacked" a solution against 1 by loading everything in the main AppDomain. The problem is that nothing can be unloaded... After some time the memory use is huge.

For this reason I eventually would consider to switch to an interpreted solution but want to remain near to a C# language because of the existing code-base. There is a bunch of libs around Vsa, S#, Script.NET, ... I need to access objects in my application from the scripts and also run methods in the scripts from my application. Do you also think that switching to an interpreted language the right strategy or should I try to add a debug mode to the existing concept by injecting code like calling a method between each line of the script to allow a step by step execution.... However the AppDomain handling remains a nightmare to handle.

It is certainly not the first time someone runs in such a situation. I could not find any FOSS wrapper/helper library to make the CodeDOM handling easier nor GUI elements to provide building blocks for a minimal debugger. Currently I built ma own GUI and step over calls in the scripts and show changes in the application objects (before/after calls) inside the GUI.

Please only refer to FOSS source/libs.

答:
There are a few interpreted options that are more dynamic but close relatives of .NET. I think I would let my audience drive the choice.

For sys-admins I would try and expose powershell commandlets and let them use that. They should be comfortable over there, and it is a very powerful and .NET friendly tool. Credit to @jmh_gr for suggesting this in the comments.

For developers I would look at a dynamic CLR implementation of a well-known language. IronPython comes to mind. F# also has an interactive scripting mode that you might be able to use if you want to stick to more official-like languages.

For non-developers I would think about using something like Boo to create my own DSL so I could make the verbage make sense.

Finally, none of these strategies are mutually exclusive. In some ways, they build on one another as they require many of the same facilities to be successful.

OwnerDisplayName: jdehaan


问:
Programming languages, positional languages and natural languages
Some programming languages are modeled on machine code, like assembly languages. Other languages are modeled on a natural language, the English language. Others are not modeled on either machine code or natural language. Languages such as PROLOG, for example, don't follow either model.

I came across this Perl module Lingua::Romana::Perligata, that allows to write programs using a syntax that is very similar to Latin.

Are there programming languages that have less positional syntax?

Are there other languages or modules that allow you to write in syntaxes inspired by other natural languages, like French, Hebrew or Farsi? There is a very long list on Wikipedia, but most of those projects are dead.

There is a related question on StackOverflow. The answer that was accepted is "Use Google".

答:
The only currently used written programming language I can think up off the top of my head is HTML. Now depending on your definition of programming language, this may or may not count.

To help you understand why there is not a lot of high usage programming languages that have less positional syntax you have to understand how most programming languages are designed.
Most programming languages are based on unambiguous grammars, mostly by the use of LL and LR grammars. In order to keep the grammars unambiguous most of the technology relies on using the ordering of the symbols and words, e.g. terminals, to make the input unambiguous. What you are looking for are languages that give up position to make the grammar unambiguous. If the compilers cannot use position to decide if the grammar is unambiguous, then the compiler needs some other hints to make the grammar unambiguous, thus prefixes such as #, %, ' and ". Another technique is to associate keywords with each value, i.e. width=10, which is what HTML does. If you create a grammar that does not use LL and LR grammars, then you have to use a different technology to resolve ambiguities which typically use backtracking which requires a large amount of computer processing to resolve the ambiguities.

Declarative languages are closest in general that I know of such as PROLOG and SQL, but again require the use of some positional values.

The only other languages that come to mind are spoken language into AI systems that process the input such as Watson, but again, do you consider this a programming language; if you consider SQL a programming language, then why not a verbal query for Watson.


问:
Writing-Reading a hashtable to a text file
I'm implementing a hashtable structure for a dictionary. Dictionary is in a text file. There are 2 words on each line. I'm generating the hashtable by using the first word as a key. I'm holding the hashtable on a list. I want to save the hashtable to a text file to use it every time. What kind of structure should I use? Is there a way to do this without reading the whole hashtable from text file?</p>

答:
You are looking for serialization.

In Python you could use pickle. In Java you can do it too. Almost every language has techniques for serialization.

If your hashtable becomes too big, you will have to use a relational database management sysyem, like MySQL, PostgreSQL, Oracle, SQL Server, etc.


问:
How do I approach this PHP/MYSQL query?
I have a reservation system that I have coded and my final task is to allow the user to enter a set of dates and then show them all available options.

The reservation table is set up with unit_id, check_in and check_out. There are twelve different unit numbers.

So I have to somehow iterate through them and find the units that have no taken dates during the date range the user has put in. Just having some trouble conceptualizing what needs to happen.

Pseudo code

```<code>$units = array (all the units);

foreach($units as $key = $value){

    Run a query searching through all reservations for that unit,
    if the unit is available, add to our $available_units array for the view later

}
</code>```

Checking availability has me stumped too though. What is the most efficient way to use the customers available date range and compare to the date ranges in the db?

答:
Lets assume that the customer wants  the date range date_from to date_to, where date_from <= date_to. You told us that you have a reservation table, let's call it reservation_table.
Using the column names you provided, i.e. reservation_table = unit_id, check_in, check_out, such that check_in <= check_out

How about the following query in mysql?

```<code>select r.unit_id from reservation_table r
  where r.check_in > date_to  OR r.check_out < date_from;
</code>```

Title: How do I approach this PHP/MYSQL query?

Body:
Lets assume that the customer wants  the date range date_from to date_to, where date_from <= date_to. You told us that you have a reservation table, let's call it reservation_table.
Using the column names you provided, i.e. reservation_table = unit_id, check_in, check_out, such that check_in <= check_out

How about the following query in mysql?

select r.unit_id from reservation_table r
  where r.check_in > date_to  OR r.check_out < date_from;


问:
Passing member variable as a method parameter
In a project, I've found a code like this:

```<code>class SomeClass
{
    private SomeType _someField;

    public SomeType SomeField
    {
        get { return _someField; }
        set { _someField = value; }
    }

    protected virtual void SomeMethod(/*...., */SomeType someVar)
    {
    }

    private void SomeAnotherMethod()
    {
        //.............
        SomeMethod(_someField);
        //.............
    }

};
</code>```

How do I convince my teammates that this is bad code?

I believe this is an unnecessary complication.  Why pass a member variable as a method parameter if you already have access to it?  This is also a violation of encapsulation.

Do you see any other issues with this code?

答:
I can think of a justification for passing a member field as a parameter in a (private) method: it makes explicit what your method depends on.

Like you say, all member fields are implicit parameters of your method, because the whole object is. However, is the full object really needed to compute the result? If SomeMethod is an internal method which only depends on _someField, isn't it cleaner to make this dependency explicit? In fact, making this dependency explicit may also hint that you can actually refactor this piece of code out of your class! (Note I assume we aren't talking about getters or setters here, but code that actually computes something)

I wouldn't make the same argument for public methods, because the caller neither knows nor cares about which part of the object is relevant to compute the result...


答:
If the function is called various times, sometimes passing that member variable in and sometimes passing something else, then it's OK. For example, I would not consider this bad at all:

```<code>if ( CalculateCharges(newStartDate) > CalculateCharges(m_StartDate) )
{
     //handle increase in charges
}
</code>```

where newStartDate is some local variable and m_StartDate is a member variable.

However if the function only ever gets called with the member variable passed to it, that's odd. Member functions work on member variables all the time. They may be doing this (depending on the language you're working in) to get a copy of the member variable - if that's the case and you can't see that, the code might be nicer if it made the whole process explicit.

Title: Passing member variable as a method parameter

Body:
In a project, I've found a code like this:

```<code>class SomeClass
{
    private SomeType _someField;

    public SomeType SomeField
    {
        get { return _someField; }
        set { _someField = value; }
    }

    protected virtual void SomeMethod(/*...., */SomeType someVar)
    {
    }

    private void SomeAnotherMethod()
    {
        //.............
        SomeMethod(_someField);
        //.............
    }

};
</code>```

How do I convince my teammates that this is bad code?

I believe this is an unnecessary complication.  Why pass a member variable as a method parameter if you already have access to it?  This is also a violation of encapsulation.

Do you see any other issues with this code?

Body:
If the function is called various times, sometimes passing that member variable in and sometimes passing something else, then it's OK. For example, I would not consider this bad at all:

if ( CalculateCharges(newStartDate) > CalculateCharges(m_StartDate) )
{
     //handle increase in charges
}

where newStartDate is some local variable and m_StartDate is a member variable.

However if the function only ever gets called with the member variable passed to it, that's odd. Member functions work on member variables all the time. They may be doing this (depending on the language you're working in) to get a copy of the member variable - if that's the case and you can't see that, the code might be nicer if it made the whole process explicit.