问:
How much detail to put into first iteration of project?
I have just started a new personal project (Python), and am writing what amounts to a "rough draft" of the program, the minimum required to do what I want to do. I am not yet putting in extensive error/exception handling or aesthetic UI elements (even in cases where I know these things will ultimately be needed), and the documentation is just enough to help future me see what I was doing.

Is it against any set principles of project design/management to start so rough? I am a scientist, not a programmer, so am not up to speed on these things. So the main question is, is there a consensus on where one should aim to fall between the two extremes of:

Write thorough, high-quality code from the start, with all the exception
handling and such that you know you will ultimately need.

Write a minimally working rough draft from the start, and go in to fill in all the
minutiae later.

Related question: When is it OK to sacrifice the "neatness" of the design to get a project done?

答:
All software design and coding concepts and patterns arise in response to some problem.  The pattern or concept is a solution to that problem.  Over time, some patterns become "well-known" as preferable solutions because they solve the problem in a way that fulfills certain requirements for consistency, familiarity, performance, maintainability, and so forth.

It follows that, if the problem that the software pattern is meant to solve doesn't exist in your particular software, then you don't need the pattern.  Further, any discussions of what patterns your software might need must also include detailed discussions of your proposed software: what is it supposed to do?  What problem does it solve?  How many users will there be?  Will the users be sharing data in some way?  And so forth.

The problem that exceptions are supposed to solve is when something happens that the code can't do anything about.  An example would be a File/Open operation where a file name is specified that doesn't exist on the storage medium.  Exceptions give the code a way to say to the caller "Something happened that prevents me from continuing, and there's nothing I can do about it, so I'm giving up."  If you don't have any places in your code where conditions like that exist, then you don't need exceptions.  Or, you can simply return an error code, and avoid the exception altogether.

As you gain experience, you will learn about software patterns and when their use is appropriate.  You will also know how much up-front design you need; again, that totally depends on the application you are writing.  Small utilities are written in a fundamentally different way from large, enterprise applications, in other words.


答:
There is no single answer, as this depends entirely on the project.  We need to think about two things here.  What is your eventual target?  How do you expect to get there?

End Result

Are you writing Mars Orbiter control software?  Then you better make damn sure you are writing the most robust code possible,  You better be check every exception is handled in a sane matter.

Are you writing a program that only you will run, and you'll only run manually every once in a while?  Then don't bother with exceptions.  Don't bother with heavy architecture.  Get it working to the point where it works for you.

How do you expect to get there?

Are you doing heavy waterfall development, where you spend lots of time figuring out what is needed, and then you will go off for months, developing?  If so, then you want to hit that target quality mentioned above fairly early.  Get all your error checking infrastructure planned out at the start.

Are you doing heavy agile development, where you are putting something together for a week or two, which will then be shown to stakeholders, who may ask for radical revisions, and where you expect to be able to iterate over many 1-2 wee sprints until you hit the target?  Then you may be better off getting something working, but fragile together fast, and only adding belts-and-suspenders as the product requirements solidify.

If you are in control over the waterfall or agile decision (which is actually a continuum not a binary choice) then make that decision based on expected change.  If you are sure you know exactly what the end result will look like, then waterfall is your best choice.  If you only have a vague notion of what you need to end up with, agile is your best choice.  (Agile is more popular these days not because it is inherently better but because the second situation is far more common.)

Now find your own answer

For most, the answer will lie somewhere in the middle.  Answer both those questions about your project, and it should lead you in a basic direction.

I can say that for myself, if I often write one-off scripts that are abysmally designed and have no error checking whatever.  I also handle production code, where error handling and architecture get large amounts of attention.  It all depends on what you are doing.

One final caveat:  If you decide you are doing one-off scripts that can be done quick-and-dirty, make sure.  Unfortunately, it often happens that quick-and-dirty scripts that do something interesting get leveraged into broad usage when others notice them.  Make sure that when this happens, time is given for hardening.

ContentLicense: CC BY-SA 3.0

Title: How much detail to put into first iteration of project?

Body:
I have just started a new personal project (Python), and am writing what amounts to a "rough draft" of the program, the minimum required to do what I want to do. I am not yet putting in extensive error/exception handling or aesthetic UI elements (even in cases where I know these things will ultimately be needed), and the documentation is just enough to help future me see what I was doing.

Is it against any set principles of project design/management to start so rough? I am a scientist, not a programmer, so am not up to speed on these things. So the main question is, is there a consensus on where one should aim to fall between the two extremes of:

Write thorough, high-quality code from the start, with all the exception
handling and such that you know you will ultimately need.

Write a minimally working rough draft from the start, and go in to fill in all the
minutiae later.

Related question: When is it OK to sacrifice the "neatness" of the design to get a project done?


问:
Is Rails 3 ready for use in production?
I'm looking to get a snapshot of Rails 3 at this point in time. We're about to start a new long term project, and I'm wondering if R3 is ready for real use. Or, if there are still a lot of bumps to be worked out. E.g. I saw questions about its compatibility with Passenger. (?)

Thanks!

答:
Rails 3 is very much ready for production use. It's in use on big sites like Shopify (you can read about their long path to Rails 3 here: http://blog.shopify.com/2010/11/16/our-upgrade-to-rails-3).

I've recently upgraded my own Rails 2.3.x app to Rails 3, and it runs fine on Passenger. I didn't encounter any compatibility problems with Passenger 3 and the site has been running on Rails 3 + Passenger for about a month now with no problems.

Since you're starting a new project, I'd strongly recommend you start on Rails 3 because frankly the upgrade to Rails 3 can be quite painful like Shopify's story.

ContentLicense: CC BY-SA 2.5

Title: Is Rails 3 ready for use in production?


问:
Breaking ASP .NET MVC application into microservices
I have a big ASP .NET MVC application which consists of several different widgets. They all display some kind of data related to stock markets, but they're actually pretty separated from one another. I'd like to break the big monolithic app into several smaller services which should be easier to maintain.

It would be pretty simple if I had only server side code written in C#, but actually I also have quite a few javascript components and also some styles and other resources. I don't know where they should be put. From the separation perspective, if some javascript files are used only by one specific widget, they should be part of its service. On the other hand, I don't know how to later integrate all the widgets and their resources, especially when there might be some common scripts used by all components.

So far I've had two ideas, none of which seems ideal:

Separate only the server side code and leave all the client side components in one common project. Js integration, minimization and management would be easier, but developers still would need to work on two different projects when updating one specific service.

Create nuget packages for each microservice with both server and client side code. What about common scripts then and files dependent on them? If I made a breaking change in common infrastructure, I would need to manually update all the dependent code. It would be much more difficult that updating files when they all reside in the same project.

Are there any better solutions?

答:
I would separate only the server side code and leave all the client side components in one common project.  I'm not bothered by your assertion that developers would have to work on multiple projects; every Visual Studio solution I've ever worked on has multiple projects, and some have many.

The only time you would create Nuget packages would be if you are using the microservices in multiple solutions.

ContentLicense: CC BY-SA 4.0


问:
Affecting culture as a newly hired developer
I've been in my first professional position for about six months now, and so I am hitting what I suppose is the pretty typical moment:

Naievely perhaps, I think there's a lot of cultural baggage on the team that holds it back (A lack of respect for documentation work, hugely scattered documentation,  infrequent code review, a disconnect between development and test etc.)

I've started trying to make my mark; setting up tooling for documentation, static analysis, etc.

Where I am lost however is in the questions of buy in: While I can try to lead by example in some areas, I do need to get the team on board. I also have to consider that my priorities don't match those of the rest of the team.

How do I get buy in, and get a good feeling for what people value? Ideas I've considered:

Team survey -- Ask about what's important to drive future efforts

Skunkworks teams: Try to recruit small groups to work on driving forward pieces they care about in their 'free' time?

Try to convince management that we need to make these kinds of changes, and try to get them part of the review process?

Or maybe I need to STFU and keep my head down and do my work.

The team is about 50 people spread across multiple teams working on a shared C++ codebase.

答:
In my professional experience (a combined 26 years in three very different workplaces, not counting grad school), there are times when a team does better with documentation, review, testing, and the like, and other times when it does worse. It can be influenced by external deadlines or a number of other factors. The "bad time" can last a lot more than 6 months, and people are less willing than usual to humor the new hire's ideas on best practices when they feel required to forgo some of their own.

Or it may be that it's always been like this in that group as long as anyone remembers. In that case, it's going to take a while to change old habits; conversely, if the whole house of cards isn't already tumbling down at this point, it can probably be propped up for enough time to implement changes gradually.


问:
Is a programming language a set of programs or a set of instructions?
From Structured Computer Organization by Tanenbum

A program is  a sequence of instructions describing how to perform a
  certain task.

When trying to see a programming language as a formal languages added with semantics, I heard that a programming language is a set of valid programs (valid according to the syntax and other aspects of the language).

When reading Structured Computer Organization by Tanenbum, I understood that a programming languages is a set of instructions, from

Each machine has a machine language, consisting of all the instructions that the machine can execute.

So I wonder if a programming language is a set of programs or a set of instructions? Thanks.

答:
From the perspective of programming language theory

I would say neither. A programming language is 3 things

A set of rules for constructing programs: the grammar of the language.

A set of rules for determining whether a particular program is a valid program without running it: the static semantics of the language*

A set of rules for actually evaluating a program to a value: the dynamic semantics (this is what most people call "semantics")

You can't just call the set of programs a programming language because we, as programmers, care very deeply about how you interpret that program. If I told you I constructed a new language called Nothyp which had the same syntax as Python (accepted the same set of programs) but ran everything backwards (different dynamic semantics) it'd be characterized as the same language if we just looked at the programs they accept!

Plus, in this form proving something like type safety, termination guarantees, or the canonical values lemma is actually reasonably pleasant.

*The static semantics capture the essence of type checking and all the other things a compiler will catch before runtime


答:
Note that the latter definition only talks about the machine language of some computer, not about programming languages in a general sense. I suppose the machine language is a programming language, but when treating programming languages as sets of programs, we can reconcile that with the latter definition by rephrasing it like this: The machine language is the set of of strings of machine instructions (or sequences of machine instructions).

Note that this nicely fits the first definition (program = sequence of instructions). That's because that definition is from an operating system developer's perspective: In that book, Tanenbaum does not care about fancy high level languages, only about binaries that can be executed by the CPU.

Also, none of those definitions is normative. There are many other useful and defensible perspectives on programs and programming languages.

Title: Is a programming language a set of programs or a set of instructions?

Body:
From Structured Computer Organization by Tanenbum

A program is  a sequence of instructions describing how to perform a
  certain task.

When trying to see a programming language as a formal languages added with semantics, I heard that a programming language is a set of valid programs (valid according to the syntax and other aspects of the language).

When reading Structured Computer Organization by Tanenbum, I understood that a programming languages is a set of instructions, from

Each machine has a machine language, consisting of all the instructions that the machine can execute.

So I wonder if a programming language is a set of programs or a set of instructions? Thanks.


答:
Why not just quote wikipedia? Nails it down in my opinion:

A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs to control the behavior of a machine or to express algorithms.
Wikipedia - Programming Language


问:
Dynamic Programming Problem - To find smallest integer number 'x' which contains only digits 1's and 0's such that x mod n = 0
To design an algorithm that will output the smallest integer number 'x' which contains only digits 1's and 0's such that x mod n = 0 and x > 0.....
For example:

2   divides 10

3   divides 111

4   divides 100

5   divides 10

6   divides 1110

7   divides 1001
and so on.

The 1's and 0's are in base 10 representation.

I know that we can solve this using the pigeon hole principle but in this problem we are interested in the smallest number.

I was thinking of using a DP approach similar to a subset sum problem where the set contains 1, 10, 100, 1000 and so on. I am not completely clear about how to formulate the recurrence relation for this problem. Can someone give some insight?

答:
Just an outline of thought.

To me, it seems bruteforce and streetsmart will beat any theoretical approach.

Example #1

If N contains a factor of 2 up to multiplicities K, then you can deduce that the lowest digits of X will have to contain at least K consecutive zeroes, because only consecutive zeroes in the lowest digits can provide factors of 2. And so on. Doesn't seem to involve any theories.

Example #2

Another streetsmart is the divisibility by 9 of decimal numbers judged by the sum of decimal digits. (More precisely it's the property of the modulo by 9. Divisibility refers to modulo giving zero. Divisibility by 3 is a simple corollary derived from the modulo by 9.) Note that by using "modulo", it is apply it to any numbers, say 13, by filtering the candidates of X with the requirement that mod(X_candidate, 9) == mod(13, 9) == 4. The requirement is necessary but not sufficient, but it helps cutting down the number of cases needed by the bruteforce.


问:
Why is instance creation the way it is?
I've learned C# over the course of the past six months or so and am now delving into Java. My question is about instance creation (in either language, really) and it's more of: I wonder why they did it that way. Take this example

```<code>Person Bob = new Person();
</code>```

Is there a reason that the object is specified twice? Would there ever be a something_else Bob = new Person()?

It would seem if I were following on from convention it would be more like:

```<code>int XIsAnInt;
Person BobIsAPerson;
</code>```

Or perhaps one of these:

```<code>Person() Bob;
new Person Bob;
new Person() Bob;
Bob = new Person();
</code>```

I suppose I'm curious if there's a better answer than "that's just the way it is done".

答:
There is a huge difference between int x and Person bob.
An int is an int is an int and it must always be an int and can never be
anything other than an int.
Even if you don't initialize the int when you declare it (int x;),
it is still an int set to the default value.

When you declare Person bob, however, there's a great deal of flexibility
as to what the name bob might actually refer to at any given time.
It could refer to a Person, or it could refer to some other class, e.g. Programmer,
derived from Person; it could even be null, referring to no object at all.

For example:

```<code>  Person bob   = null;
  Person carol = new Person();
  Person ted   = new Programmer();
  Person alice = personFactory.functionThatReturnsSomeKindOfPersonOrNull();
</code>```

The language designers certainly could have made an alternative syntax that would
have accomplished the same thing as Person carol = new Person() in fewer symbols,
but they still would have had to allow Person carol = new Person()
(or make some strange rule making that particular one of the four examples above illegal). They were more concerned with keeping the language "simple" than in writing
extremely concise code.
That may have influenced their decision not to provide the shorter alternative syntax,
but in any case, it wasn't necessary and they didn't provide it.

Title: Why is instance creation the way it is?

Body:
There is a huge difference between int x and Person bob.
An int is an int is an int and it must always be an int and can never be
anything other than an int.
Even if you don't initialize the int when you declare it (int x;),
it is still an int set to the default value.

When you declare Person bob, however, there's a great deal of flexibility
as to what the name bob might actually refer to at any given time.
It could refer to a Person, or it could refer to some other class, e.g. Programmer,
derived from Person; it could even be null, referring to no object at all.

For example:

  Person bob   = null;
  Person carol = new Person();
  Person ted   = new Programmer();
  Person alice = personFactory.functionThatReturnsSomeKindOfPersonOrNull();

The language designers certainly could have made an alternative syntax that would
have accomplished the same thing as Person carol = new Person() in fewer symbols,
but they still would have had to allow Person carol = new Person()
(or make some strange rule making that particular one of the four examples above illegal). They were more concerned with keeping the language "simple" than in writing
extremely concise code.
That may have influenced their decision not to provide the shorter alternative syntax,
but in any case, it wasn't necessary and they didn't provide it.


问:
Should I prefer classes or singletons in JavaScript/Node?
This question applies especially to Node.js, but also to JavaScript in general.

I started working on a simple web app in Node.js. I'm relatively new to Node and JavaScript, and come mainly from C# and Java.

In my app, obviously I need objects. In C#, I would create a class and instantiate it to get an object.

In Node.js however, I have two options:

Creating a 'class' in a Node module of it's own, and later requireing and instantiating it (like I would do in C#).

Creating an object in a Node module of it's own, and using it
later by requireing it directly.

I'm trying to decide what the better approach in general is.

I'm leaning strongly towards approach 1, because it lets me instantiate the desired class anytime I want, instead of using a global singleton.

On the other hand, maybe it feels like the better approach simply because I'm used to it, coming from C#. Possibly I'm just trying to do C# in JS?

So my question would be: in Node and generally in JavaScript, when in need of an object to implement a piece of functionality, should I go with classes or with plain objects?

答:
My insight in this matter might not qualify for a full answer, but I think you are comparing to valid approaches, who's differences aren't a matter of style, but of solving different problems.

If you fear of trying to do C# in Javascript, maybe you should start by questioning a more essential premise of yours:

In my app, obviously I need objects.

More often than not, in Javascript this statement is not as unquestionable as you might think. Probably, if you are considering a singleton as an option, you are just looking for a namespace where you can expose a set of functions. In this case, you could just add these functions to module.exports, which is already an object that acts as the namespace of the module.

This is an interesting read about the many patterns that can be used when designing the interface of a module in Node.js.


问:
how often do we need to do appraisal for a developer?
I have this question since my friend told me that if we have frequent appraisal such as 4 months or 6 months once, people will be turned to a money minded.

But I am thinking this in another aspect like, people will be getting feedback and boost quickly than one year appraisal. We do not need to increase the salary much. But the token advancement would help them to get some refreshment.

答: I would say once a year for an in depth cover-all-bases & semi-formal (i.e. documented) appraisal, plus an open-policy door that invites discussion of more immediate issues, whenever they arise.</p>


问:
What's the point with HATEOAS on the client-side?
As I currently understand HATEOAS is basically all about sending together with each response links with information about what to do next. One simple example is easily found on the internet: a banking system together with an account resource. The example shows this response after a GET request to an account resource

```<code>GET /account/12345 HTTP/1.1 HTTP/1.1 200 OK
<?xml version="1.0"?>
<account>
    <account_number>12345</account_number>
    <balance currency="usd">100.00</balance>
    <link rel="deposit" href="/account/12345/deposit" />
    <link rel="withdraw" href="/account/12345/withdraw" />
    <link rel="transfer" href="/account/12345/transfer" />
    <link rel="close" href="/account/12345/close" />
</account>
</code>```

Together with the data there are links telling what can be done next. If the balance is negative we have

```<code>GET /account/12345 HTTP/1.1 HTTP/1.1 200 OK
<?xml version="1.0"?>
<account>
    <account_number>12345</account_number>
    <balance currency="usd">-25.00</balance>
    <link rel="deposit" href="/account/12345/deposit" />
</account>
</code>```

So that we can only deposit. That's all fine, if we are using Fiddler or making requests with the browser we can easily see what can be done. This kind of information is useful then for us to discover the API's capabilities and the server is decoupled from the client.

The point, however, is that when we build a client, like a SPA with Javascript, or an Android app or many other things, I can't see how HATEOAS continues being relevant. What I mean is the following: when I'm coding the SPA in javascript, I must know what can be done in the API in order to write the code.

So I need to know the resources, the methods supported, what they expect to receive and what they give back in order to write the ajax calls to the server and even in order to build the UI. When I build the UI, I must know that after requesting the account, one can for example deposit into it, or I won't be able to provide this option on the UI. Also, I'll need to know the URI to make the deposit to build the ajax call.

What I mean is, when we make requests to the API, links do allows us to discover and use the API better, but when we build a client, the app we are building won't simply look at the links and then by itself render the correct UI and make the right ajax calls.

So, how is HATEOAS important for the clients? Why do we bother with HATEOAS anyway?

答:
the app we are building won't simply look at the links and then by
  itself render the correct UI and make the right ajax calls

In fact, this is exactly what HATEOAS will give the UI.  Not what is possible, but when it is possible.  A formal HATEOAS like HAL, as the question states, gives links that indicate what is possible.  But when those links show up depends on the state of the application.  So, the links can change on the resource over time (based on actions that have already been performed).

This allows us to build a UI that contains all the possible states, but not be concerned with when those states become active.  For example, the presence of the rel="deposit" can directly tell the UI when it is OK to render the make deposit form.  Which then allows the user to enter a value and submit using the link.


问:
Deployments, another unsolved problem in software engineering
Why is it so hard to package and deploy software? I want to understand what exactly is the inherent complexity of creating self-contained binaries? Currently it seems that golang is the only game in town when it comes to almost completely solving the deployment problem but even go has some issues with versioning dependencies. Why aren't more languages solving this problem at the compiler/language level?

Note that I'm not talking about library code. I'm talking about an actual application or a service that needs to get to a production environment as quickly and as reliably as possible.

答:
I don't believe this is a language problem. This is more of a software architecture or run-time architecture or operating system architectural concern (note, I don't say problem).

If every software deployment was a self-contained binary then every software package would be an absolutely HUGE install. You would need to replicate every dependent library and run-time piece of software needed by the software in question.

So really, unless you wanted to ship a 6 gig version of solitaire, external dependencies are a good thing.


答:
There is a very simple and practical approach to this, which works for a wide range of small to medium size projects. Even though it probably won't work well for Mars Explorers.

First, work out what you want the system to do and note down each of the individual features. This can be as sophisticated as a whole user story board or as simple as a few bullet points jotted down on a piece of paper in front of you. But it is important you know what you want it to do.

Based on that draw up the general structure of the system. Again, this is very often just a quick drawing of the different classes/modules and how they relate to each other, but might be as complex as a whole document. The important thing is that you have some sort of idea of how you are going to implement the system. But, this is probably going to get refined as you work on it, so don't try to go to complex and detailed.

Out of all these features work out what the key things are that the program needs to do - the core features.

Then implement them one-by-one. Now the key thing here is that to actually make sure that once you implemented a feature this is done and fully working - ideally this is accompanied by a unit test that makes sure it keeps working. I usually go on the assumption that I will be so busy that I will never have time to come back to the feature and fix it.

Once the core features are implemented, I generally try to put the system to use as close to the production environment as possible. This gives you a) any bugs you might have missed earlier and b) you get a good idea of the priority of the next features.

Then you can keep implementing the remaining features as needed.

Code Quality vs. Features

With the above in mind, I tend to sacrifice features over quality of code, if I have to make a deadline. Simply because, at least in my line of work, when I finish something my management assumes it is done. And that they can give me the next task. I don't have a lot of time making code nicer after the fact.

Now, what about exception handling?

If you don't want to implement that off the bat, you could just list that as another feature on the list. And when you get to it you can implement that. But most likely in your case there are probably many other things that are more important first.

However, there is a minimum requirement for exceptions: Make sure the user is notified if anything goes wrong - no matter how ugly the output may be. Don't swallow exceptions somewhere.


答:
Dependencies. Take a very simple Python application. I can distribute it as a script. It will work on some machines, and won't work on others, because the script is using Python 3 and those machines have only Python 2 installed, or no Python at all.

So now, I need to make sure, during deployment, that a specific version of Python is either available or will be installed during deployment.

How would you solve that at compiler/language level?...

See also: Has anyone nailed dependency management?

Configuration. Take a very simple service which receives calls from the outside. It works on my machine. I deploy it on the server, and it stops working. Nothing happens: the service receives no calls, no matter what I do.

This is because the server has a firewall which blocks the port used by the service.

Which means that my deployment script should open the specific port. If I have total control over the servers and know that every server uses UFW as the only firewall, the task is relatively easy. If I don't have such control and has to support multiple firewalls, the task becomes more complex.

There is nothing a compiler/language can do for me there.

Infrastructure. Take an example of a web app which uses MongoDB. If there is no MongoDB server, the app won't work. This means that database should be deployed as well, probably on a different server. Thus, I should create a dedicated virtual machine for the database, deploy MongoDB, and configure the deployed web app by setting the proper connection string.

But then, it appears that I need a failover, so now I need two database servers, and I need to change the connection string accordingly. More importantly, I need to configure the failover so the data replicates as expected after one of the database machines is deployed.

Then, I don't want to lose all the data if the VMs which host the database are destroyed, so I make backups. Now, the deployment script should also handle the recover from the latest backup.

Those three points are just a small subset of all the challenges you may have during deployment.

In all those points, neither your compiler, nor the programming language can help. This is because most of the deployment challenges are not inherent to the language/compiler/framework you use.

But wait, there are instead a bunch of tools which are specific to deployments:

Package managers. Have you used npm in Node.js, pip in Python or NuGet in C#/Visual Basic? Their handling of dependencies is particularly exciting, and they make it quite easy to deploy a small software product. Have you used apt-get? The sole fact that you can simply type apt-get install something and let the tool do all the job, no questions asked, is nearly magic.

Configuration managers/infrastructure automation tools. Tools such as Chef, Puppet or OpenStack do a great job of making it easy to automate deployments. It doesn't mean that you can say "Make me a MongoDB failover" and watch the result (although, it does exactly that for simple cases), but at least, you can have a reproducible, automated process which makes your life much easier.

Title: Deployments, another unsolved problem in software engineering

Body:
Why is it so hard to package and deploy software? I want to understand what exactly is the inherent complexity of creating self-contained binaries? Currently it seems that golang is the only game in town when it comes to almost completely solving the deployment problem but even go has some issues with versioning dependencies. Why aren't more languages solving this problem at the compiler/language level?

Note that I'm not talking about library code. I'm talking about an actual application or a service that needs to get to a production environment as quickly and as reliably as possible.


问:
Why use Creational patterns in Java?
How are Creational patterns useful? Most of the material I came across explains the use case to "solve common problems associated with object creation, improve flexibility".

I can think of just two similar cases where these might help:

Encapsulating object creation code into a factory like class, so that all object creation code is in one place, and any modifications would require changes only in one place.

Making object creation dynamic, whereby the required concrete type can be returned based on some parameters.

I am not able to exactly understand what problems creational patterns solve. What unfavourable consequences could one face by not using creational patterns?

It would be great if some one could elaborate on this with real code examples.

答:
In Java, if DerivedFoo: BaseFoo, saying foo = new DerivedFoo(boz); will construct a new "blank" DerivedFoo instance and call the a DerivedFoo constructor that can take boz as a parameter.  That constructor must in turn call one of BaseFoo's constructors before it is allowed to do much of anything with the object under construction or with the passed-in parameter.  Once BaseFoo's constructor returns, BaseFoo will have no further control over the object under construction.

Note that there are many cases where code might know that it needs something that derives from DerivedFoo, but might not need a newly-created object of that exact type.  Among other things:

In some cases, often identifiable based upon passed-in parameters, some other derivative of DerivedFoo might be better.

In some cases, especially with immutable types, the client may be better served by a pre-existing object than by a new one.

Some kinds of objects need to notify outside objects when they are created and ready for use, but the calling sequence for constructors doesn't notify the base-class object when the most derived constructor has finished executing, and doesn't even provide a terribly convenient way for a constructor to know if other more-derived constructors have yet to execute.

Factory methods can easily overcome all of these problems, since they can return new or pre-existing objects, and can invoke base-class initialize() method after the most derived constructor is finished.

Title: Why use Creational patterns in Java?


问:
Controller in MVC
Alright so it is an essential part of OOP that one class should only do one thing, and it makes sense. In practice I've seen that classes which don't obey this rule get thick and cluttered.

So I was thinking and I kinda can't wrap my head around how the controller fits into this. If each method of a controller should represent a different page from the website, then this doesn't really make much sense to me. Yes the pages may be related, such as /user/edit and /user/view which are in the same controller, but if I'm going to display one of those pages, loading the other method and possibly many more is completely pointless.

It's probably that I'm missing something since people have been using this approach in major frameworks, but can you help me figure out what?

答:
IMHO, Model-View-Controller (MVC) design pattern purpose is to separating your application concern into Data (model), Presentation (view) and Business logic (controller) to increase the reusability and maintainability of your code[1][2]. In MVC design pattern, the controller component contains every method in your application which have the same domain. Lets say, you will put every method that related to user into UserController (login, register, add, delete, etc) so with SalesController which will contains every method related to sales.

So, i think its more clearer and cleaner to grouping your method which has same domain into the one controller instead of creating controller for every method :). Although i never test the performance (ex: class loading in your case) but i believe php and web server will handle it for you in the background.

Title: Controller in MVC


答:
They are counterproductive. They are supposed to motivate your people, but in many case it does just the inverse. In some companies I've visited, it's also a way to seek & destroy slackers! I'm against performance reviews or any individual appraisals for the following reasons:

Appraisers (bosses of course) are biased. Personal feelings often take over. I can't be objective.

When there are multiple appraisers, it's just luck because of the point above.

Most employees that does is best and get a negative appraisal will become much less productive than before. It's the spiral.

So it changes the target of your employees. It's not company goal anymore, it's their own and individual yearly or quarterly appraisal.

This tend to create competition within departments, or worse, within teams!

This tend increase individualism a lot. Which is the worse things that could happen to your company

Stephen Covey, author of the 7 Habits and more importantly the The 8th Habit which describe the damage of yearly appraisal, once said

"The so- called boss should become a humble servant and a helper to the employees"

In Software Development, "Peopleware," by Tom DeMarco and Timothy Lister explains the same and propose other ways to motivate employees.

What are the alternatives?

Improve the work place instead of saving on it. Avoid open spaces, buy high performance machines, free drinks & foods

Encourage innovation. Your people are smarter than you think

Don't cut quality. Your people must be proud of what they do

Abolish overtime. Except in some very exceptional circonstances such as security breach that must be fixed

Prefer open minded people

Your people get feedback constantly already:

when a user/customer send them an email saying the product is just amazing

when someone ask for their help

when someone do his best to help them

when they are exited to go to work

when they know they are a part of something great

when their boss trust them and sincerly think they are the professionals

when their coleagues smile at them frequently

when CruiseControl says "All build are good"

when everyone is happy around them

When they receive bad feedback they know:

it's an opportunity to learn

they really did their best, they can't please everybody

Encourage efforts, not performances. Creating a top performers is creating 1% of winners and 99% of loosers.

Further reading on the subject: Abolishing Performance Appraisals: Why They Backfire and What to Do Instead

Title: how often do we need to do appraisal for a developer?

Body:
I have this question since my friend told me that if we have frequent appraisal such as 4 months or 6 months once, people will be turned to a money minded.

But I am thinking this in another aspect like, people will be getting feedback and boost quickly than one year appraisal. We do not need to increase the salary much. But the token advancement would help them to get some refreshment.


问:
How to efficiently handle related data in MVC?
Talking about MVC with servlets and JSP's, in a context about products and manufacturers , when querying the application for a list of products:

the servlet loads a list of products from the database in a List object (or similar);

the servlet sets that list as attribute of the request and forwards the request to a JSP;

the JSP retrieves the list from the request and displays its contents on the webpage.

If the above is correct, my question is: how do I load products manufacturers (let's suppose that each product contains the id of its manufacturers)?

A common approach I saw around is that when the JSP loops inside the list object, upon showing each product is calls some other class method which finally runs a query on the database.

There are two things that I dislike about this approach:

it breaks the MVC pattern;

several, usually separate, queries are run on the database, potentially loading the same data (i.e. when two products come from the same manufacturer).

Is the above true? Are there better approaches that solve the problem?

So far I'm thinking about making a servlet load the manufacturers data in a separate object (e.g. a Map) along with the products List: both objects are set to the request, and then the JSP can access both when rendering the page.

A (potentially dangerous) drawback of this idea is that it requires more memory to hold all the informations; anything else?

答:
you can use ORM (object relational mapping) like JPA or Hibernate. when you are using ORM in your model, you dont need to re-query the related object because ORM will handle it for you automatically. for example:

define your model class and it's relationship:

```<code>class Product
{
    Manufacturer manufacturer;

    //setter and getter
}

class Manufacturer
{
    Long id;
    String name;

    //setter and getter
}
</code>```

calling the model in the controller's method:

```<code>public Result showProductList()
{
   List<Product> products = ProductModel.get();
   return Result.ok().render("products", products);
}
</code>```

and you can call the manufacture name in product in from your product model.

```<code><c:forEach var="product" items="${products}">
    <option value ="10"><c:out value="${product.manufacturer.name}"/></option>
</c:forEach>
</code>```

disclaimer:
the example code above is not the real code. I just want to show the big picture about using the ORM in your code. using this approach you won't break the MVC design pattern (because you don't need to re-query the object from your view)

Body:
you can use ORM (object relational mapping) like JPA or Hibernate. when you are using ORM in your model, you dont need to re-query the related object because ORM will handle it for you automatically. for example:

define your model class and it's relationship:

class Product
{
    Manufacturer manufacturer;

    //setter and getter
}

class Manufacturer
{
    Long id;
    String name;

    //setter and getter
}

calling the model in the controller's method:

public Result showProductList()
{
   List<Product> products = ProductModel.get();
   return Result.ok().render("products", products);
}

and you can call the manufacture name in product in from your product model.

<c:forEach var="product" items="${products}">
    <option value ="10"><c:out value="${product.manufacturer.name}"/></option>
</c:forEach>

disclaimer:
the example code above is not the real code. I just want to show the big picture about using the ORM in your code. using this approach you won't break the MVC design pattern (because you don't need to re-query the object from your view)


答:
One common benefit of a creational pattern is to change program behavior from one run to another. This could be done by a command-line argument, for example. Perhaps specifying a switch to enable functionality results in a factory creating a different type of object, say by creating a different type of output writer for a file vs. standard output. Maybe there are two types of controllers sharing a common interface. One is interactive, one must be fed in its inputs and runs without user interaction.

I do have a concrete example of a creational pattern: Log4j. The following XML snippet is copied from the sample XML configuration in the Log4j manual.

The code that reads this configuration will create an appender, layout, and filters based on the values specified in this section. It will link them together into a complete, usable object graph.

```<code><Appender type="Console" name="STDOUT">
  <Layout type="PatternLayout" pattern="%m MDC%X%n"/>
  <Filters>
    <Filter type="MarkerFilter" marker="FLOW" onMatch="DENY" onMismatch="NEUTRAL"/>
    <Filter type="MarkerFilter" marker="EXCEPTION" onMatch="DENY" onMismatch="ACCEPT"/>
  </Filters>
</Appender>
</code>```

While most applications will not delegate much of the object creation specification to external configurations, this is used quite heavily in certain applications. At one of my previous jobs there were quite a few factories and singletons used to customize behavior in the application and the implementations were specified in property files. When requesting an instance the code will check the class name to load (which must be the enclosing class or a subclass), allowing customer extensions.

This particular code is a brief example of how to construct a factory based on a system property. It would be possible to set a system property to use a subclass which might then override the createWidget() method to create different widgets.

```<code>public class MyFactory {

  public static MyFactory createFactory() {
    String implName = System.getProperty(MyFactory.class.getName());
    if (implName == null) {
      return new MyFactory();
    }
    else {
      try {
        Class<?> impl = Class.forName(implName);
        return impl.newInstance();
      }
      catch (Exception e) {
        throw (e instanceof RuntimeException
            ? (RuntimeException) e : new RuntimeException(e));
      }
    }
  }

  public Widget createWidget() { ... }
}
</code>```

Title: Why use Creational patterns in Java?

Body:
How are Creational patterns useful? Most of the material I came across explains the use case to "solve common problems associated with object creation, improve flexibility".

I can think of just two similar cases where these might help:

Encapsulating object creation code into a factory like class, so that all object creation code is in one place, and any modifications would require changes only in one place.

Making object creation dynamic, whereby the required concrete type can be returned based on some parameters.

I am not able to exactly understand what problems creational patterns solve. What unfavourable consequences could one face by not using creational patterns?

It would be great if some one could elaborate on this with real code examples.

Body:
One common benefit of a creational pattern is to change program behavior from one run to another. This could be done by a command-line argument, for example. Perhaps specifying a switch to enable functionality results in a factory creating a different type of object, say by creating a different type of output writer for a file vs. standard output. Maybe there are two types of controllers sharing a common interface. One is interactive, one must be fed in its inputs and runs without user interaction.

I do have a concrete example of a creational pattern: Log4j. The following XML snippet is copied from the sample XML configuration in the Log4j manual.

The code that reads this configuration will create an appender, layout, and filters based on the values specified in this section. It will link them together into a complete, usable object graph.

<Appender type="Console" name="STDOUT">
  <Layout type="PatternLayout" pattern="%m MDC%X%n"/>
  <Filters>
    <Filter type="MarkerFilter" marker="FLOW" onMatch="DENY" onMismatch="NEUTRAL"/>
    <Filter type="MarkerFilter" marker="EXCEPTION" onMatch="DENY" onMismatch="ACCEPT"/>
  </Filters>
</Appender>

While most applications will not delegate much of the object creation specification to external configurations, this is used quite heavily in certain applications. At one of my previous jobs there were quite a few factories and singletons used to customize behavior in the application and the implementations were specified in property files. When requesting an instance the code will check the class name to load (which must be the enclosing class or a subclass), allowing customer extensions.

This particular code is a brief example of how to construct a factory based on a system property. It would be possible to set a system property to use a subclass which might then override the createWidget() method to create different widgets.

public class MyFactory {

  public static MyFactory createFactory() {
    String implName = System.getProperty(MyFactory.class.getName());
    if (implName == null) {
      return new MyFactory();
    }
    else {
      try {
        Class<?> impl = Class.forName(implName);
        return impl.newInstance();
      }
      catch (Exception e) {
        throw (e instanceof RuntimeException
            ? (RuntimeException) e : new RuntimeException(e));
      }
    }
  }

  public Widget createWidget() { ... }
}


问:
What is the rule for nested loop code?
I am new to programming and currently learning Java from Stanford free learning course.  There was this assignment that I had trouble translating my algorithm into code.  I feel like I have a misconception about nested loops.

My question in this code:

```<code>while (frontIsClear()) {   //LET THIS REFER AS BOOLEAN 1
  putBeeper();             //LET THIS REFER AS STAT 1
  if (frontIsClear()) {    // LET THIS REFER AS BOOLEAN 2
    move();                //LET THIS REFER AS STAT 2
  }
}
</code>```

If BOOLEAN 1 is TRUE but BOOLEAN 2 is FALSE  then will STAT 1 work or will it terminate everything?

I understand STAT 2 won't work because BOOLEAN 2 is false but I just don't get this loop inside condition etc.

答:
Every loop in Java (and most, but not all programming languages) has a loop conditional which is checked every iteration. It works just like an if statement: the conditional is a boolean expression. If it evaluates to true, the loop executes. If it evaluates to false, the loop stops and control flows to the next statement after the loop.

In this code, frontIsClear() is used to control both the while loop and the if conditional. If the method returns false in either case, the body of that construct (compound statement, everything between { and }) will not execute.

Title: What is the rule for nested loop code?


问:
REST API - Should API Return Nested JSON Objects?
When it comes to JSON APIs is it good practice to flatten out responses and avoid nested JSON objects?

As an example lets say we have an API similar to IMDb but for video games. There are a couple entities, Game, Platform, ESRBRating, and GamePlatformMap which maps Games and Platforms.

Lets say you request /game/1 which fetches the game with ID 1 and it returns the game object with the platforms and esrbRating nested.

```<code>{
  "id": 1,
  "title": "Game A",
  "publisher": "Publisher ABC",
  "developer": "Developer DEF",
  "releaseDate": "2015-01-01",
  "platforms": [
    {"id":1,"name":"Xbox"},
    {"id":2,"name":"Playstation"}
  ],
  "esrbRating": {
    "id": 1,
    "code": "E",
    "name": "Everyone"
  }
}
</code>```

If you are using something like JPA/Hibernate it may automatically do this for you if it is set to FETCH.EAGER.

The other option is to simply the API and add more end points.

In that case when /game/1 is requested just the game object is returned.

```<code>{
  "id": 1,
  "title": "Game A",
  "publisher": "Publisher ABC",
  "developer": "Developer DEF",
  "releaseDate": "2015-01-01",
}
</code>```

If you want the platforms and/or ESRBRating you would have to call the following:

/game/1/platform
/game/1/esrb

This method seems like it could potentially add several more calls to the server depending on what data the client needs and when they need it.

There was one last thought I had where you would have something like this returned.

```<code>{
  "id": 1,
  "title": "Game A",
  "publisher": "Publisher ABC",
  "developer": "Developer DEF",
  "releaseDate": "2015-01-01",
  "platforms": ["Xbox","Playstation"]
}
</code>```

However this assumes they don't need the IDs or whatever other information may be associated with those platform objects.

I asking in general what is the best way to structure your JSON objects returned from your API. Should you try to stay as close to your entities as possible, or is it fine to use Domain Objects or Data Transfer Objects? I understand the methods will have trade offs, either more work on the data access layer or more work for the client.

I would also like to hear an answer related to using Spring MVC as the backend technology for the API, with either JPA/Hibernate or MyBatis for persistence.

答:
Another alternative (using HATEOAS). This is simple, mostly in practice you add a links tag in the json depending on your use of HATEOAS.

http://api.example.com/games/1:

{
  "id": 1,
  "title": "Game A",
  "publisher": "Publisher ABC",
  "developer": "Developer DEF",
  "releaseDate": "2015-01-01",
  "platforms": [
    {"_self": "http://api.example.com/games/1/platforms/53", "name": "Playstation"},
    {"_self": "http://api.example.com/games/1/platforms/34", "name": "Xbox"},
  ]
}
```

<p><code>http://api.example.com/games/1/platforms/34</code>:</p>

<pre class="lang-javascript prettyprint-override"><code>{
  "id": 34,
  "title": "Xbox",
  "publisher": "Microsoft",
  "releaseDate": "2015-01-01",
  "testReport": "http://api.example.com/games/1/platforms/34/reports/84848.pdf",
  "forms": [
    {"type": "edit", "fields: [] },
  ]
}
</code>```

You can off course embed all data in all listing but that will likely be way too much data. This way you can embed the required data and then load more if you really want to work with it.

The technical implementation can contain caching. You can cache the platforms links and names in the game object and send it instantly without having to load the platforms api at all. Then when required you can load it.

You see for example that I added some form information. I did that to show you there can be much more information in a detailed json object than you would even want to load in the listing of games.

Body:
Another alternative (using HATEOAS). This is simple, mostly in practice you add a links tag in the json depending on your use of HATEOAS.

http://api.example.com/games/1:

{
  "id": 1,
  "title": "Game A",
  "publisher": "Publisher ABC",
  "developer": "Developer DEF",
  "releaseDate": "2015-01-01",
  "platforms": [
    {"_self": "http://api.example.com/games/1/platforms/53", "name": "Playstation"},
    {"_self": "http://api.example.com/games/1/platforms/34", "name": "Xbox"},
  ]
}

http://api.example.com/games/1/platforms/34:

{
  "id": 34,
  "title": "Xbox",
  "publisher": "Microsoft",
  "releaseDate": "2015-01-01",
  "testReport": "http://api.example.com/games/1/platforms/34/reports/84848.pdf",
  "forms": [
    {"type": "edit", "fields: [] },
  ]
}

You can off course embed all data in all listing but that will likely be way too much data. This way you can embed the required data and then load more if you really want to work with it.

The technical implementation can contain caching. You can cache the platforms links and names in the game object and send it instantly without having to load the platforms api at all. Then when required you can load it.

You see for example that I added some form information. I did that to show you there can be much more information in a detailed json object than you would even want to load in the listing of games.


答:
You don't have to build a dynamically generated interface. Though it could be nice it's not required. If you cannot build a dynamic interface just use the links and you are done. Disadvantage is that you are again hard linked to the backend and will crash if something changes.

Using the dynamic layout can be quite simple btw:

```<code>links.forEach(function(link) {

  switch(link.rel) {

    case 'deposit':
      showDepositButton();
      break;

    case 'withdraw':
      loadWithdrawForm(link.href);
      showWithdrawButton();
      break;
  }

});
</code>```

It saves you in your client code like:

```<code>if (balance <= 0 && negativeBalanceAllowed === false) {
  showWithdrawButton();
}
</code>```

You can implement an allowed negative position (by borrowing money for example) without changing your client.

Title: What's the point with HATEOAS on the client-side?

Body:
As I currently understand HATEOAS is basically all about sending together with each response links with information about what to do next. One simple example is easily found on the internet: a banking system together with an account resource. The example shows this response after a GET request to an account resource

```<code>GET /account/12345 HTTP/1.1 HTTP/1.1 200 OK
<?xml version="1.0"?>
<account>
    <account_number>12345</account_number>
    <balance currency="usd">100.00</balance>
    <link rel="deposit" href="/account/12345/deposit" />
    <link rel="withdraw" href="/account/12345/withdraw" />
    <link rel="transfer" href="/account/12345/transfer" />
    <link rel="close" href="/account/12345/close" />
</account>
</code>```

Together with the data there are links telling what can be done next. If the balance is negative we have

```<code>GET /account/12345 HTTP/1.1 HTTP/1.1 200 OK
<?xml version="1.0"?>
<account>
    <account_number>12345</account_number>
    <balance currency="usd">-25.00</balance>
    <link rel="deposit" href="/account/12345/deposit" />
</account>
</code>```

So that we can only deposit. That's all fine, if we are using Fiddler or making requests with the browser we can easily see what can be done. This kind of information is useful then for us to discover the API's capabilities and the server is decoupled from the client.

The point, however, is that when we build a client, like a SPA with Javascript, or an Android app or many other things, I can't see how HATEOAS continues being relevant. What I mean is the following: when I'm coding the SPA in javascript, I must know what can be done in the API in order to write the code.

So I need to know the resources, the methods supported, what they expect to receive and what they give back in order to write the ajax calls to the server and even in order to build the UI. When I build the UI, I must know that after requesting the account, one can for example deposit into it, or I won't be able to provide this option on the UI. Also, I'll need to know the URI to make the deposit to build the ajax call.

What I mean is, when we make requests to the API, links do allows us to discover and use the API better, but when we build a client, the app we are building won't simply look at the links and then by itself render the correct UI and make the right ajax calls.

So, how is HATEOAS important for the clients? Why do we bother with HATEOAS anyway?

Body:
You don't have to build a dynamically generated interface. Though it could be nice it's not required. If you cannot build a dynamic interface just use the links and you are done. Disadvantage is that you are again hard linked to the backend and will crash if something changes.

Using the dynamic layout can be quite simple btw:

links.forEach(function(link) {

  switch(link.rel) {

    case 'deposit':
      showDepositButton();
      break;

    case 'withdraw':
      loadWithdrawForm(link.href);
      showWithdrawButton();
      break;
  }

});

It saves you in your client code like:

if (balance <= 0 && negativeBalanceAllowed === false) {
  showWithdrawButton();
}

You can implement an allowed negative position (by borrowing money for example) without changing your client.


问:
Say I wanted to create a cross platform program that does not require a runtime/VM, am I stuck with C/C++?
Let's say that I'm a theoretical programmer hunting for a cross platform programming language, what are my options. This language must satisfy this list of requirements:

It must not require the user to install extra programs or runtimes (Clarification: I don't mind linking libraries etc. If I can package them with the application. The program must not require the user to install anything to be able to run my game. Basically I just want the user to be able to download my program and run it straight out of the box.)

Run on Mac, Windows and Linux

It must compile down to an executable, or the runtime be packaged with the executable (E.g. how Love2d allows Lua programmers to create executables, by embeding the runtime in the executable.) The larger size and slower speed is an issue though, so most people would avoid.

Free (as in beer)

Preferable but not entirely necessary:

Free (as in speech)

It can be used to program mobile apps (Android and iOS) as well.

Fast

Small executable sizes.

Mature and stable (as in syntax and the tools surrounding it)

So how about it? If a programmer wants to create a program that satisfies these parameters are C and C++ their only options? Java sort of satisfies these requirements but does require the runtime environment to be installed (Doesn't it?). Are there any languages out there that satisfy this niche? Not necessarily to the same maturity as C and C++ though.

*Edit: I disagree with this question being put on hold, I'm not asking which language I'm going to take up next, which is off topic and subjective. I'm specifically asking about languages that satisfy these requirements, which is not subjective. I'm also not creating a poll, I'm asking for specific pieces of technology that satisfy this list of requirements. The help center suggests leaving a comment here to get it re-opened, so would it be possible to re-open this question for discussion?

答:
If it can run in a browser, then JavaScript is available, as well as languages that compile to JavaScript like Dart, CoffeeScript, ClojureScript, and TypeScript. These are your only good choices for running on mobile devices as well as desktops and Chromebooks.

For compiled desktop apps, there's Go. At a less mature state, there's D, Rust, and Nim.


答:
You could use some languages with compiled implementations available on all the 3 platforms, e.g. Ocaml or Common Lisp or Haskell or Scheme (or maybe Go, Rust, Opa, Haxe, ...) You could also use implementations which compiles to C or C++ code, in particular Bigloo, Hop, etc.... (At some point Mozart/Oz was doing so)

BTW, notice that even C has some runtime component: the C standard library (libc.so on Linux).

You could also embed some interpreter in your program (e.g. Lua or Guile...)

You might want to use static linking to embed the runtime in your executable. It has drawbacks.

Be aware that a programming language is a specification (often in some English document) which might have several implementations (often, some free software).

It must not require the user to install extra programs or runtimes

I feel that this requirement is ambiguous, very fuzzy and ill-defined: in some sense, when I am browsing any modern site in HTML5+Javascript, some programs (in Javascript) are installed inside my browser (but a naive user won't notice that). And would you accept to have the user download some file once (i.e. getting a self-contained ELF file for Linux/x86-64, or some .exe file for Windows) before using your program? Also, a hello-world C++ or C program requires some "installation" (either compilation of the source code, e.g. for most free software, or downloading a binary executable which will be specific to the user platform). BTW, even in C or C++ you can have dependency hells, such as DLL hells.

addenda

Notice also that with C or C++ on POSIX like systems (typically Linux) you could consider meta-programming : you'll write a program in C which sometimes generates some C code (in some temporary file), and ask the C compiler to compile that new temporary file. In so doing you don't require anything additional since you already need a C compiler in the first place. So if you generate /tmp/emittedcode.c in your program at runtime, you would run (e.g. using system(3) or popen(3)...) a compilation command such as gcc -O -Wall -fPIC -shared /tmp/emittedcode.c -o /tmp/emittedcode.so which produces a shared library that you could dynamically load using dlopen(3) and retrieve symbols in it using dlsym(3). With care you'll find equivalent API in Windows (or use some toolkit like Qt or Gtk which is wrapping them, providing some common dynamic loader API which would be the same for every supported OS).

Also, consider using some JIT compilation library like GCCJIT, libLLVM, libjit, lightning, asmjit, ... You could use them to develop your own language implementation (or consider compiling to C) or just generate useful code at runtime.

Title: Say I wanted to create a cross platform program that does not require a runtime/VM, am I stuck with C/C++?

Body:
Let's say that I'm a theoretical programmer hunting for a cross platform programming language, what are my options. This language must satisfy this list of requirements:

It must not require the user to install extra programs or runtimes (Clarification: I don't mind linking libraries etc. If I can package them with the application. The program must not require the user to install anything to be able to run my game. Basically I just want the user to be able to download my program and run it straight out of the box.)

Run on Mac, Windows and Linux

It must compile down to an executable, or the runtime be packaged with the executable (E.g. how Love2d allows Lua programmers to create executables, by embeding the runtime in the executable.) The larger size and slower speed is an issue though, so most people would avoid.

Free (as in beer)

Preferable but not entirely necessary:

Free (as in speech)

It can be used to program mobile apps (Android and iOS) as well.

Fast

Small executable sizes.

Mature and stable (as in syntax and the tools surrounding it)

So how about it? If a programmer wants to create a program that satisfies these parameters are C and C++ their only options? Java sort of satisfies these requirements but does require the runtime environment to be installed (Doesn't it?). Are there any languages out there that satisfy this niche? Not necessarily to the same maturity as C and C++ though.

*Edit: I disagree with this question being put on hold, I'm not asking which language I'm going to take up next, which is off topic and subjective. I'm specifically asking about languages that satisfy these requirements, which is not subjective. I'm also not creating a poll, I'm asking for specific pieces of technology that satisfy this list of requirements. The help center suggests leaving a comment here to get it re-opened, so would it be possible to re-open this question for discussion?


问:
Is it OK to have multiple asserts in a single unit test?
In the comment to this great post, Roy Osherove mentioned the OAPT project that is designed to run each assert in a single test.

The following is written on the project's home page:

Proper unit tests should fail for
  exactly one reason, that’s why you
  should be using one assert per unit
  test.

And, also, Roy wrote in comments:

My guideline is usually that you test
  one logical CONCEPT per test. you can
  have multiple asserts on the same
  object. they will usually be the same concept being tested.

I think that, there are some cases where multiple assertions are needed (e.g. Guard Assertion), but in general I try to avoid this. What is your opinion? Please provide a real world example where multiple asserts are really needed.

答:
I don't know of any situation where it would be a good idea to have multiple assertions inside the [Test] method itself. The main reason people like to have multiple Assertions is they are trying to have a one [TestFixture] class for each class being tested. Instead, you can break up your tests into more [TestFixture] classes. This allows you to see multiple ways in which the code may not have reacted in the way you expected, instead of just the one where the first assertion failed. The way you achieve this is you have at least one directory per class being tested with lots of [TestFixture] classes inside. Each [TestFixture] class would be named after the specific state of an object you will be testing. The [SetUp] method will get the object into the state described by the class name. Then you have multiple [Test] methods each asserting different things you would expect to be true, given the object's current state. Each [Test] method is named after the thing it is asserting, except perhaps it might be named after the concept instead of just an English readout of the code. Then each [Test] method implementation only needs a single line of code where it is asserting something. Another advantage of this approach is it makes the tests very readable as it becomes quite clear what you are testing, and what you expect just by looking at the class and method names. This will also scale better as you begin to realize all the little edge cases you want to test and as you find bugs.

Usually this means that the final line of code inside the [SetUp] method should store a property value or return value in a private instance variable of the [TestFixture]. Then you might assert multiple different things about this instance variable from different [Test] methods. You also might make assertions about what different properties of the object under test are set to now that it is in the desired state.

Sometimes you need to make assertions along the way as you are getting the object under test into the desired state in order to make sure you did not mess up before getting the object into the desired state. In that case, those extra assertions should appear inside the [SetUp] method. If something goes wrong inside the [SetUp] method, it will be clear that something was wrong with the test before the object ever got into the desired state you intended to test.

One other problem you may run into is you may be testing an Exception that you expected to be thrown. This can tempt you into not following the above model. However, it can still be achieved by catching the exception inside the [SetUp] method and storing it into an instance variable. This will allow you to assert different things about the exception, each in it's own [Test] method. You can then also assert other things about the object under test to make sure there were no unintended side effects from the exception being thrown.

Example (this would be broken up into multiple files):

namespace Tests.AcctTests
{
    [TestFixture]
    public class no_events
    {
        private Acct _acct;

        [SetUp]
        public void SetUp() {
            _acct = new Acct();
        }

        [Test]
        public void balance_0() {
            Assert.That(_acct.Balance, Is.EqualTo(0m));
        }
    }

    [TestFixture]
    public class try_withdraw_0
    {
        private Acct _acct;
        private List<string> _problems;

        [SetUp]
        public void SetUp() {
            _acct = new Acct();
            Assert.That(_acct.Balance, Is.EqualTo(0));
            _problems = _acct.Withdraw(0m);
        }

        [Test]
        public void has_problem() {
            Assert.That(_problems, Is.EquivalentTo(new string[] { "Withdraw amount must be greater than zero." }));
        }

        [Test]
        public void balance_not_changed() {
            Assert.That(_acct.Balance, Is.EqualTo(0m));
        }
    }

    [TestFixture]
    public class try_withdraw_negative
    {
        private Acct _acct;
        private List<string> _problems;

        [SetUp]
        public void SetUp() {
            _acct = new Acct();
            Assert.That(_acct.Balance, Is.EqualTo(0));
            _problems = _acct.Withdraw(-0.01m);
        }

        [Test]
        public void has_problem() {
            Assert.That(_problems, Is.EquivalentTo(new string[] { "Withdraw amount must be greater than zero." }));
        }

        [Test]
        public void balance_not_changed() {
            Assert.That(_acct.Balance, Is.EqualTo(0m));
        }
    }
}
```


问:
PHP: A config file in .ini or .php format?
I'm working on a huge CMS system, and I asked myself what configuration format I should use.

There are two common formats for configuration files. The first one is an INI file, containg all the configuration properties. Then you can simply parse this INI file using build in PHP functions. A second option is to use a PHP file containing a regular PHP array with these configuration properties.

Now, it's easier to edit an INI file, but a PHP file give's you more options, for example it allows you to add a function which retrieves one of the configuration options while reading the configuration file.

Note: The PHP configuration file would only contain an array of configuration, no initialization functions or anything. (This is possible of course, but it's not implemented by default)

Now, what is recommend for me to use as configuration file? What is the most common format for a configuration file? Should I go for simplicity with the INI files, or with a more dynamic one using PHP.

One thing to note, this is not for personal usage. I'm planning to release the CMS system soon, and a lot of websites are scheduled already to change to my CMS system.

答: You said that a lot of websites are already scheduled to change to your CMS system, so it sounds like a question for them. Will these be managed by people so programming illiterate that they would be more comfortable editing an INI file that a PHP file with simple options? Would the loss in speed from parsing the INI file be an issue for them? Would they prefer the added flexibility a PHP config file would allow? Should the security concerns of using an INI file matter to them? Or perhaps you should allow both. Perhaps some people will appreciate the ease of editing an INI file and others the advantage of a PHP file. It seems the advantages of only having a PHP config file usually outweigh that of an INI file and that of having both. Therefore, perhaps it would normally only search for a PHP file, but in the case that it is started with special options, the system could be instructed to search for an INI file or even both. If necessary, it could be instructed which config file would have the higher priority should some of the same configuration options be in both.</p>


问:
How to add cases to large legacy code base project?
There is a legacy project full of C++ code. As a MFC GUI project, it contains lots of businesses logic out of control and beyond average level programmer to understand.
To work on such GUI project, is there common techniques to add test cases/harnesses?</p>

答:
To problem with this projects is that you don't want to change the code without adding unit tests, but you usually can't and unit tests without changing the code.

If your project is like a typical legacy project, than you have large classes with lot of really long functions, without a clear role.

My strategy is the following:

Try to identify the roles of a huge class (usually there is a dozen).

Try spliting up the class alongside with these roles. Start with the simplest. Try changing as little code as possible, an mainly just move functions to the new classes.

Each time a chunk is done, test manually.

If you managed to split down a smaller class add unit tests, and continue with the next.

This is a really long and tireing process, and there are no silver bulets. I usually revert my changes a lot and try again with a differen approach. And manual testing is really important. The best is if you have someone who used this software a lot and can check if it really works the way it did before.

Good luck with this!


答:
For legacy GUI applications you would benefit two ways:

Business logic track: ask sb with business knowledge for descriptive info and write UI end-to-end automated tests. You get a good test suite for regression.

Code contemplation track: if I were to write unit tests for legacy code I would do it only either for refactored or debugged code. IMHO there is no much use unit testing legacy code just to obtain regression tests set. This is why

Title: How to add cases to large legacy code base project?

Body:
There is a legacy project full of C++ code. As a MFC GUI project, it contains lots of businesses logic out of control and beyond average level programmer to understand.
To work on such GUI project, is there common techniques to add test cases/harnesses?</p>


问:
How should I compare two database tables - with SQL or using Java?
I have two tables with different structure. I should compare ID from 1st table with ID of the intermediate table and then comapre TXT field of the intermediate table with TXT field of the 2nd table.

If there are missing records, or different values for TXT field in 1st and 2nd table I should add flag to the record in the 2nd table and recreate this record with additions from the 1st table.

I have two ways to do it. Using Java with JDBC or using SQL (or PL/SQL). But what way is correct for performance and future support?

答:
Unless you have something which the application must supply all the time, I think it would be best to let the database related stuff be handled by the database itself.

This will allow you to have the DB to do all the heavy lifting, while allowing the application to remain as lightweight as possible so that it can handle whatever it is that the user needs doing.

EDIT: As per your comment.

From my experience, leaving all the calculations on the application, creates more problems then it solves. Unless the calculations you are doing belong exclusively to how will the data interact with the user, meaning that the application should handle all operations which deal with how will the data be presented to the user.

Doing any operations which strictly involves data, such as, get all the users with a given field, or as in your case, synchronization should be left at a DB level. This will allow you to:

Leave most of the heavy lifting at a DB level. DB's are usually good at what they do, so if you let them do their stuff, your application will be more lightweight (and most likely more responsive). This should in turn make the users happy because the application is not clunky.

Save resources: When you pull data from your DB, you are opening a connection and keep it open until you are done transferring data. Connections are expensive resources which should be used only when necessary. Pulling all the information in the DB so that you can operate on it, and then send it back means that the connection will be hogged for quite some time. If you have many applications using the DB, this could mean that the application will most likely not scale very well.

The above can lead to bandwidth issues if you have your application and DB running on different machines. This can make maintaining the application more expensive.

Having a stored procedure doing logic will provide you with better flexibility to apply changes. If you have the logic at a DB level, you can just make the change in one place to get the changes you need without having to issue a new application. This would then mean that you can be certain that all of your users are running the same logic, as opposed to having users running version n of the application, while others running version n + 1.


问:
How can I ask my boss (in a polite way) to comment his code?
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?

答:
You're in the 'deep end' and, in my opinion, that's the best way to learn. Not because you're looking at stuff you don't have a clue about, but because it forces you to be more resourceful and find out what components play which role in a system you're new to.

It doesn't help that your boss is too busy to handle somebody who is inquisitive (and you're totally within your rights to be inquisitive; you're keen to learn, which is good). But, unfortunately, asking your senior to change their style and approach for the sake of your learning may not go down too well, especially since you're dealing with somebody you say is busy.

Being sat in front of thousands of lines of code you're not familiar with is the norm. You can't always have it explained in black and white with comments. However for the sake of learning while you're new to it, if you feel you definitely have to ask him for comments - maybe explain why. Explain it's because of the fact you don't want to bother him with questions as he's often busy. Not only will this come across a lot less like you're telling him to do something, but it also opens the floor to discussions on how he might, instead, prefer to put question asking time aside.


答:
If your boss has no time to answer all of your question, why do you think he will have time for commenting his legacy code? And moreover, what makes you think his comments would really describe the bits and pieces you do not understand for now? To my experience, trying to change your bosses programming style by just asking him will not work, politeful or not.

Best thing you can do in such a situation: comment the parts of the code you need to understand to do your work by yourself  - once you have understood those parts, of course, and after getting a commitment from your boss that this will be ok. If you or your boss fear you could break something by adding comments, add those in a separate branch and ask your boss if he will take the time to review your comments before they get merged to the trunk. Since your boss has only a restricted time budget, try to figure out what a certain part does first by yourself by investing a reasonable amount of time. If you really get stuck, write your question down to a list and ask your boss, for example, once a day instead of disturbing him any 30 minutes. To my experience, this approach works with most people, even if they are very busy, as long as they are willing to help you - which is surely the case in your situation.

This way, you are sure you get the comments you need, and your boss will see where you need additional information, and if you got things right. And as long as you restrict yourself to comment only the non-obvious things, there is a good chance your comments will increase the overall quality of the code base, which might not only bring benefit not just to you, but also to everyone else who has to deal with the code, including your boss.

Title: How can I ask my boss (in a polite way) to comment his code?

Body:
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?


问:
Who fixes bugs in a team?
In an agile software development team, who would be the one to fix the bugs introduced in an update?

The developer who writes the feature?

Someone else specialized specifically in debugging with a certain title?

The best developer in the team?

答:
In an agile software development team, who would be the one to fix the bugs introduced in an update?

In an agile software development team, one hopes the notion of code ownership doesn't exist. In such a team, collective code ownership should reign supreme.

In such a team, the person to fix the code is the first person to notice the bug - either due to their own testing, a report from another team (say testers) or a customer. Every member is just as competent to fix any bug as anyone else.

That also means that bugs don't languish, waiting for person X to come back from vacation. Or if person X has gone from the company, there are others that can pick up without trouble.

(also see the different definitions discussed by Martin Fowler)

Assuming you are not working in such a team - still anyone should pick up the bug. And verify the fix without someone in the know.

The developer who writes the feature?

Possibly. If no one else can possibly fix it. Many bugs are trivial and can be fixed by anyone. Having collective ownership means that whoever fixes the bug gets to learn about the new bits of code - so more than one person can work on that bit.

Someone else specialized specifically in debugging with a certain title?

I've never heard of "senior debugger" positions. Hope to never hear of them. Frankly, debugging is part of the job. Everyone should be able to be effective at it.

The best developer in the team?

Poor fellow. Wouldn't do anything but debug stuff all day. Wonder how long it would take that person to quit.

Oh. And who decided on that? Kinda subjective, not to mention political.

Again - everyone in the team should be comfortable debugging and fixing any piece of the codebase. Or if not everyone, most people should.

Title: Who fixes bugs in a team?


问:
Why was Python's popularity so sudden?
Python first appeared in 1991, but it was somewhat unknown until 2004, if the TIOBE rankings quantify anything meaningful.

What happened?  What caused the interest in this 13 year old language to go through the roof? Is there a reason that Python wasn't considered a real competitor to Perl in its first decade of existence? Is there a reason that Python didn't continue in relative obscurity for another ten years?

I personally think that Python is a very nice language, and I'm glad that I'm not the only one. But it doesn't have corporate backing or a killer feature that would explain a sudden rise to relevance.

Does anyone know the story?

答: There are some aspects of python that made it look, frankly, archaic. Things that made you feel like you were coding on punched cards on a mainframe. Like having indent spacing matter to code blocks. Little stuff like that caused a lot of folks to dismiss the language after a very brief look. I suspect that hurt it pretty bad in the early days. Especially in the crowd that had lived in those types of environments for years and wanted nothing but to get away from the mainframe and out to the web.</p>

Title: Why was Python's popularity so sudden?


答:
the thing with Agile is its up to you to decide what is the best approach and process to use.

So, in this case, its down to your team to decide. Forget what anything on the internet (o some overpriced course!) tells you, find the best way that works for you. That's agile.

Don't be afraid to try difference ways, though I'd probably start with 'everyone in the team is equally responsible for problem resolution'. If it turns out that someone is best placed to resolve certain issues, and everyone is happy with that, then that's the way to go. (though if I were PM for the team I'd expect more than 1 person to know each area just in case the single-point-of-knowledge quits o dies in a horrible bus accident). If the team prefers to have equal ownership of all code, then you have to deal with knowledge transfer and that's good too. Its all down to what works best for your team, not someone else's team who do different work or work in different ways.

Title: Who fixes bugs in a team?

Body:
In an agile software development team, who would be the one to fix the bugs introduced in an update?

The developer who writes the feature?

Someone else specialized specifically in debugging with a certain title?

The best developer in the team?


答:
First, crawling through thousands of lines of unfamiliar code and feeling lost is how every software project is, everywhere, from the beginning of time.

The biggest difference between you and an experienced programmer is that you aren't used to it.

A few points to keep in mind:

With enough effort, every bit of code is understandable. A lot of people feel frustrated if they can't figure something out within a few minutes. Be more patient than that.

A good boss is as open as possible to interruptions and questions. A good employee tries as hard as possible to minimize interruptions and questions. Be conscious of that.

Interruptions are more costly than questions. You can make better use of your time and your boss's time by consolidating your discussions, and by never ending a conversation feeling confused.

Your boss is a better programmer than you. (Probably.) That's not to say that you can't be stronger in some areas, but overall his expertise is greater. Until you have a lot of experience, make sure you're learning from his expertise as much as you can.

If you're sure that more comments would significantly help the code, ask your boss. "It's difficult for me to understand what is going on in some places. When I do figure things out, do you mind if I add comments?" Maybe he hates comments.  Maybe he'll love it. Maybe he'll be indifferent.

In the end, however, it's possible that a couple months from now you'll remember asking this and think, "Huh, I wonder what I had a problem with? This isn't that bad. Hm, well, no matter."


答:
Deployment is easy. You package up your binaries and reference any dependant projects it needs. Then you deploy the package and binaries to a well-nown location and anyone can install it, and whatever dependancies they do not already have, with a single call.

Of course, if you're not using a Linux repo then you'll have to use whatever (inferior :) ) deployment mechanism your OS supports.

But that still doesn't handle per-installation specific things, such as adding users which is something you cannot deploy automatically as it changes per site. Sure, you can make this easier and a end-user can build deployment scripts using a tool such as puppet or chef and deploy a customised setup.

Even then, there are advances in deployments - look at virtualised application systems such as Docker. this allows you to build up a system (eg pre-deployed) and then ship it in its own little world, isolated from the rest of thr OS so it doesn't conflict with any other application that is installed.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
About 7 years ago I worked at a bespoke software shop that decided to sell one of its products.  It was an end-to-end operations suite for some industry.  Well, this industry wasn't known for being super technological, so somehow we ended up providing third-party technical support for their servers and IT infrastructure instead of farming it out to independent small business IT consultants.

One day, a customer's server encountered disk corruption.  The server we had sold them was configured with an Adaptec RAID controller, set up for a RAID 1 mirror.  Their application database was toast.  They hadn't performed backups in months.  The backups they had performed were unusable.  They ended up losing 8 months of data.  They hired an IT consultant to handle this investigative work.

Phone calls ensued, and the sales manager (known for promising impossible features) apparently told them it would be taken care of, and wrote it up in a contract.

The sales manager promised the customer that we would ensure that the application database and any other application-related files would never be replicated by RAID controllers if the files were considered to be corrupt.  No configuration should be necessary either.  Yep.  We were told to deliver this functionality in 2 weeks, or the customer would fire us.

So the program manager -- who had some large enterprise CRM products, and other serious development successes, under his belt -- and I had a meeting with the COO, and the sales manager.  The program manager was detailing how insane, impossible, and insanely impossible this was.  The sales manager (military background) would simply scream in his face (literally!), "I don't care!  How hard can it be to make the RAID thing not RAID?!  Their data would be fine on the other drive if the RAID thing hadn't screwed it up!"

At the end of that meeting, the program manager quit with a zero-day notice.  So I was now tasked with this.  Over the next week, I petitioned both Adaptec and LSI Logic to provide an engineer for a conference call, simply to laugh in the face of the sales manager.

Ultimately, they obliged, and held up their end of the bargain.  And they went into detail how ridiculously unfeasible it was.  The guy from LSI was particularly harsh - he didn't sugar coat anything.

I didn't have to implement the feature.  One I did have to implement was a custom security scheme requested by a customer, that would allow them to toggle any of the application's controls - on a control by control basis - as visible, disabled, enabled, read-only, or read-write.  In theory, there were 146,000 combinations.  And if you accidentally screwed up by say... disabling a control group, you'd have inadvertent side effects.  Needless to say, when I was given the ultimatum that it had to be implemented, I also quit with a zero-day notice.


答:
I agree with gbjbaanb...

There's absolutely no right answer here.

Fixing a bug does means 3 different things:

The developer responsible for fixing the bug gain experience in that area of the project. This can be familiarity with that code, or familiarity with the business domain that code handles (depends on the kind of the bug).

It allows other people to go on with their work. Lots of times bugs interfere other developers, and they usually interfere with QA, and integration testing.

It removes a malfunction from your product allowing you to ship it, or show it to your clients\ users. This is very important and saves you from unemployment.

Also regarding the first point, if a developer is responsible for fixing a bug, it doesn't mean he doesn't get assistance or mentoring from others. Personally a lot of times I had to mentor (read babysit) new developers who were assigned to fixing bug I was responsible for, so in the future they could work on those areas by themselves.

How do you actually decide who fixes which bug?

You, your team, your team leader, need to weigh in the costs and benefits. whether its better someone new works on it? or someone experienced who is less familiar with that area? maybe the guy who actually wrote it? maybe someone more experienced who knows that area very well? what other assignments are there? how urgent is this bug? are you near a release? etc.

Title: Who fixes bugs in a team?


答:
As I currently understand HATEOAS is basically all about sending together with each response links with information about what to do next

HATEOAS is a lot more than just links. It is "hyper media" as the engine of application state.

What is missed in your description is the content type, the formal definition of the hyper media that is passed between client and server.

HTML is an example of hyper media, and an example of why HATEOS works. The HTML page itself is the engine that allows the client (ie the user) to move through the site. A browser with just an ability to render HTML present to the user a fully navigable website. It is not simply that it passes links to the other pages but it passes them in a meaningful way that gives context to the links and in a fashion that allows the browser to construct a navigable site.

And most importantly the browser can do this with ZERO up front understanding of the website itself. The browser only knows HTTP and HTML. Based on that simple understanding it can present the New York Times to the user to navigate through.

This holds even if the "user" is another computer program. The hyper media itself should define the context of navigation.