答:
When reviewing code, I apply the following rules:

Always use const for function parameters passed by reference where the
function does not modify (or free) the data pointed to.

```<code>int find(const int *data, size_t size, int value);
</code>```

Always use const for constants that might otherwise be defined using a #define or an enum.  The compiler can locate the data in read-only memory (ROM) as a result (although the linker is often a better tool for this purpose in embedded systems).

```<code>const double PI = 3.14;
</code>```

Never use const in a function prototype for a parameter passed by
value.  It has no meaning and is hence just 'noise'.

```<code>// don't add const to 'value' or 'size'
int find(const int *data, size_t size, int value);
</code>```

Where appropriate, use const volatile on locations that cannot be changed by the program but might still change.  Hardware registers are the typical use case here, for example a status register that reflects a device state:

```<code>const volatile int32_t *DEVICE_STATUS =  (int32_t*) 0x100;
</code>```

Other uses are optional.  For example, the parameters to a function within the function implementation can be marked as const.

```<code>// 'value' and 'size can be marked as const here
int find(const int *data, const size_t size, const int value)
{
     ... etc
</code>```

or function return values or calculations that are obtained and then never change:

```<code>char *repeat_str(const char *str, size_t n)
{
    const size_t len = strlen(str);
    const size_t buf_size = 1 + (len * n);
    char *buf = malloc(buf_size);
    ...
</code>```

These uses of const just indicate that you will not change the variable; they don't change how or where the variable is stored. The compiler can of course work out that a variable is not changed, but by adding const you allow it to enforce that.  This can help the reader and add some safety (although if your functions are big or
complicated enough that this makes a great difference, you arguably have other
problems). Edit - eg. a 200-line densely coded function with nested loops and many long
or similar variable names, knowing that certain variables never change might
ease understaning significantly.  Such functions have been badly designed or
maintened.

Problems with const.  You will probably hear the term "const poisoning".
This occurs when adding const to a function parameter causes 'constness' to
propagate.

Edit - const poisoning: for example in the function:

```<code>int function_a(char * str, int n)
{
    ...
    function_b(str);
    ...
}
</code>```

if we change str to const, we must then ensure that fuction_b also takes
a const.  And so on if function_b passes the str on to function_c,
etc.  As you can imagine this could be painful if it propagates into many
separate files/modules.  If it propagates into a function that cannot be
changed (eg a system library), then a cast becomes necessary.  So sprinkling
const around in existing code is perhaps asking for trouble.  In new code
though, it is best to const qualify consistently where appropriate.

The more insidious problem of const is that it was not in the original
language. As an add-on it doesn't quite fit.  For a start it has two meanings
(as in the rules above, meaning "I'm not going to change this" and "this cannot be modified").  But more than that, it can be dangerous. For example, compile and
run this code and (depending upon the compiler/options) it may well crash when
run:

```<code>const char str[] = "hello world\n";
char *s = strchr(str, '\n');
*s = '\0';
</code>```

strchr returns a char* not a const char*.  As its call parameter is
const it must cast the call parameter to char*.  And in this case that
casts away the real read-only storage property. Edit: - this applies generally to vars in read-only memory. By 'ROM', I mean not just physical ROM but any memory that is write-protected, as happens to the code section of programs run on a typical OS.

Many standard library functions behave in the same way, so beware: when you
have real constants (ie. stored in ROM) you must be very careful not to
lose their constness.

Body:
While getting my code reviewed here the issue of using the const keyword came up. I understand that it is used for implementing read-only behaviour on variables.

I am confused about what are the various situations when it can be useful.

Should it be used for the sake of clarity in function prototypes?

Should it be used as a security measure during code development?

Should it be used in the scope of various functions for declaring run-time constants?

Should it be used at all?

These question are just examples of the confusion that I am facing. The general confusion is

When should be the const keyword used in C programming?

What are the various types of benefits that can be gained by using this keyword in C?

Are there any cons of using const keyword?

It has been pointed that this question may be too broad due to all these questions in the detail of my question. I just wanted to clarify that these questions are just to clarify the confusion regarding the main question.

When and for what purposes should the const keyword be used in C for variables?

It can also be rephrased as

The proper use of const keyword in C` with the pros and cons of the same.

Body:
When reviewing code, I apply the following rules:

Always use const for function parameters passed by reference where the
function does not modify (or free) the data pointed to.

int find(const int *data, size_t size, int value);

Always use const for constants that might otherwise be defined using a #define or an enum.  The compiler can locate the data in read-only memory (ROM) as a result (although the linker is often a better tool for this purpose in embedded systems).

const double PI = 3.14;

Never use const in a function prototype for a parameter passed by
value.  It has no meaning and is hence just 'noise'.

// don't add const to 'value' or 'size'
int find(const int *data, size_t size, int value);

Where appropriate, use const volatile on locations that cannot be changed by the program but might still change.  Hardware registers are the typical use case here, for example a status register that reflects a device state:

const volatile int32_t *DEVICE_STATUS =  (int32_t*) 0x100;

Other uses are optional.  For example, the parameters to a function within the function implementation can be marked as const.

// 'value' and 'size can be marked as const here
int find(const int *data, const size_t size, const int value)
{
     ... etc

or function return values or calculations that are obtained and then never change:

char *repeat_str(const char *str, size_t n)
{
    const size_t len = strlen(str);
    const size_t buf_size = 1 + (len * n);
    char *buf = malloc(buf_size);
    ...

These uses of const just indicate that you will not change the variable; they don't change how or where the variable is stored. The compiler can of course work out that a variable is not changed, but by adding const you allow it to enforce that.  This can help the reader and add some safety (although if your functions are big or
complicated enough that this makes a great difference, you arguably have other
problems). Edit - eg. a 200-line densely coded function with nested loops and many long
or similar variable names, knowing that certain variables never change might
ease understaning significantly.  Such functions have been badly designed or
maintened.

Problems with const.  You will probably hear the term "const poisoning".
This occurs when adding const to a function parameter causes 'constness' to
propagate.

Edit - const poisoning: for example in the function:

int function_a(char * str, int n)
{
    ...
    function_b(str);
    ...
}

if we change str to const, we must then ensure that fuction_b also takes
a const.  And so on if function_b passes the str on to function_c,
etc.  As you can imagine this could be painful if it propagates into many
separate files/modules.  If it propagates into a function that cannot be
changed (eg a system library), then a cast becomes necessary.  So sprinkling
const around in existing code is perhaps asking for trouble.  In new code
though, it is best to const qualify consistently where appropriate.

The more insidious problem of const is that it was not in the original
language. As an add-on it doesn't quite fit.  For a start it has two meanings
(as in the rules above, meaning "I'm not going to change this" and "this cannot be modified").  But more than that, it can be dangerous. For example, compile and
run this code and (depending upon the compiler/options) it may well crash when
run:

const char str[] = "hello world\n";
char *s = strchr(str, '\n');
*s = '\0';

strchr returns a char* not a const char*.  As its call parameter is
const it must cast the call parameter to char*.  And in this case that
casts away the real read-only storage property. Edit: - this applies generally to vars in read-only memory. By 'ROM', I mean not just physical ROM but any memory that is write-protected, as happens to the code section of programs run on a typical OS.

Many standard library functions behave in the same way, so beware: when you
have real constants (ie. stored in ROM) you must be very careful not to
lose their constness.


问:
How do I introduce clean code?
My team has about 18 members and the code is generally good, using TDD and good specifications makes for working code. But I think they abuse comments in favor of writing cleaner, more readable code.

I would like to introduce them to the concept and I'm wondering how can I do that on a larger scale without sitting with each and every one of them on their code and explaining how it could be improved.

This is different from the suggested duplicate because I believe I already know how to write clean code.  What I'm looking for is how do I introduce my team to writing clean code?

答:
I'm wondering how can I do that on a larger scale without sitting with each and every one of them on their code and explaining how it could be improved

Short answer:

nothing else than regular code reviews can fix this

you don't have to do all the code reviews by yourself, especially when your team has 18 people

How you organize your code reviews is up to you, of course, for example, you could insist that before some new code is checked in (into your VCS), every dev picks an available peer and asks him kindly to proof-read the code. You could also do code reviews on a more formal basis, or after check-ins - choose whatever works best in your team.

ContentLicense: CC BY-SA 3.0

Title: How do I introduce clean code?


答:
There are a few ways you could do that.

First way, use your languages features. In java you could things features such as Abstract, Final, Public, Private, inheritance, interfaces, delegates, events. That would prevent them from messing the code at the object oriented level. You  could go a step further and implement design patterns. Designed patterns were adapted in the 90s by programmers, but first developed by an architect whose name was Alexander Christopher. Design patterns have the strong advantage of templating the code design, and imposing a design structure.Read the article the gang of four. There is also a site where different design patterns are implemented.

At the class level, you could use things like getters and setters, that would clean up the code and make it more manageable. Tell your team in general to use prefixes for function names, such as get, set, is (for returning booleans).

I read from some book that is called "clean code" that you should use up to 20 functions in a class, and each class should be classified by functionality. Number of lines in the function should also be limited. So why not to tell your team to follow such policy?

Teach your team to write shorter code if you can, use trinary expressions instead of if or else, use switch instead of many if and else, use recursion instead of some loops, do do while loops instead of while loop . Avoid the use of labels when in loop, avoid many condition statements in ifs or for loops, avoid long loops (comment at the end of loop closing braces if loop is long),avoid many nested loops.

To sum up, enforce a template on all the code design through abstract classes, inheritance interfaces and design patterns overall. Use short well named functions, group them by class, allows use the right accessors (try to use uncommon accessors like 'final', 'sealed'), use getters and setters, as they are also a means of code control.  Try to address and comment how to write clean, short and effective control flow. Use the api more as it offers prebuilt functionality, dont try to come up with your own functionality as it will result in more code, which is also less tested.

*I was in a messy code situation too many times to know what clean code is!

Title: How do I introduce clean code?

Body:
My team has about 18 members and the code is generally good, using TDD and good specifications makes for working code. But I think they abuse comments in favor of writing cleaner, more readable code.

I would like to introduce them to the concept and I'm wondering how can I do that on a larger scale without sitting with each and every one of them on their code and explaining how it could be improved.

This is different from the suggested duplicate because I believe I already know how to write clean code.  What I'm looking for is how do I introduce my team to writing clean code?


问:
Learning basic graphics programming
After learning the basics of computing simple die throwing games and calendar applications, I want to explore simple graphics - drawing and moving around geometric objects is ok to start with, eventually adding pixel graphic of course.

I've taken an introductory Java course but would rather do it in C++, Python or a combination of them (that's what we will eventually be using in school). I also want to learn the principles behind it, not just blindly applying incomprehensible syntax to make the compiler happy.

Some posts seem to imply SFML is a solid choice, so I thought I'd get a book covering it and work through it, but there only seems to be ONE book on SFML available, and that one hasn't been reviewed at all. Not in the mood for a $30 gamble, so I'm feeling kind of lost!

How should I approach learning basic graphics programming?

答:
I have appreciated the Processing language and The Nature of Code ( http://natureofcode.com/book/ ) for this purpose.

Processing ( processing.org ) is built on top of Java, but requires almost none of the boilerplate you would expect with Java. As far as language goes, I wouldn't worry too much about what language you learn these skills in as they are somewhat language agnostic. The skills will transfer. What I like about Processing is that it's all about getting to the point of, e.g., what is a normalized vector and what's it for.

The Nature of Code walks you through getting graphics on the screen w/ Processing and the physics you are trying to represent.

And both are free.

Speaking a bit more generally, I would recommend a framework with as few 'moving parts' outside of the concept you are trying to learn as possible.

Title: Learning basic graphics programming


答:
Your first problem is to decide what you mean by clean code.  You may know what you mean, but I expect you will find a range of opinion amongst 18 team members.  Without first agreeing (or dictating, if you are so minded) what is good and what is bad, you have no chance of achieving it.

As a suggestion, why not get each team member to submit a piece of what they consider good code to the Code Review StackExchange site (https://codereview.stackexchange.com/) and see what reviewers make of it (if it is C, I will review it :-). It doesn't need to be a large amount - just a few functions or a class, or maybe even just a header file.  If the team is good, they should expect to get only minor remarks. The reviews will give you some independent basis for  progressing towards cleaner code.

Title: How do I introduce clean code?


问:
Should I ask/tell my boss before freelancing?
I am currently working as an intern at a consulting firm. I am soon to move to a full time employee once I graduate next semester, and I love working there. However, as a student, I lack money and I have met a business owner outside of work who has offered to hire me for some freelance web development.

Because I met this individual outside of work, I feel it would not be a conflict of interest to freelance for him. However, the work his is wanting me to do is very similar to what I already do for my current boss.

Should I speak with my boss before considering the offer?

Edit: I understand that I cannot take IP from work, and I am not in a contract, I'm employed at will.

答:
My written employment agreement states that I'll get permission from my boss before taking outside employment. That included when I ran for election (after he stopped laughing hysterically [oddly enough, my father also laughed hysterically when I told him I was standing for office], he said yes). Things that the company has accepted co-workers for outside employment include part-time retail (that guy is paying for 3 divorces) and part-time schlepping boxes at UPS.

Whether you think it is the business of my boss (and I don't think it is), the argument is that they don't want your side work affecting your main job's performance.

ContentLicense: CC BY-SA 2.5


问:
What's the difference between college-level and corporate programming?
I have just completed my Bachelors degree in IT field. I have deep interest in coding and really want to be a professional in it. Now, apart from college courses, I have been learning programming(C#) on my own (college level programming is too basic). Now I feel I need a little more time to be close to professional programmer. But some of my seniors say that corporate world programming is too different from bookish programming, hence there is no point in wasting time. (They are not programmers themselves, this may be probably what they heard).

Would I benefit by reaching an advance level of C#? or as mediocre level is sufficient to break interviews, higher levels do not matter to firms because they rely on their training purely to teach how things work in corporate world and learning more won't help me much?
Please if there are some professional programmers who can help, I promise this is something which about every student interested in programming want to ask at my stage. "How do you actually change from learner to professional in field of programming?" - keep learning until you are perfect or joining a firm is must once basics are covered?

答:
This question is based on an invalid assumption:

"How do you actually change from learner to professional in field of
  programming?"

You become a professional by getting paid to do it. You never stop being a learner. If you do, your career is over.

Go out in the world and get a job. Your enthusiasm for learning is an asset.


问:
When should we stop work and make tool?
As a software engineer, we are always eager to get effective tools to boost our productivity.
And in our daily work, we are often unsatisfactory with the existing tools and would like to have better ways such as better GDB script config, Vim script and some Python script to make boring things automatic.

However, it is actually a trade-off since making tools also needs time and energy. It does not give productivity boosting immediately. Therefore, how do you judge whether it is time to stop work and to make some tools to ease your future pain?

答:
This is a big problem in my experience. Tool building is usually left to a motivated developer who stops work to build the tool. This often interferes with the development even if it provides value. Tool building needs to be viewed as an integrated part of the development "Process".

I remember attending code reviews where header errors would result in scheduling another review. Many of these could have been detected by a tool. e.g. incorrect sloc counts, missing requirement, formatting errors. My tool written in perl generated the header from the delivered code and validated requirements from an Oracle database. It was not part of our "Process" so in the short run building the tool was viewed as delaying delivery.

The entire team needs to periodically stop and see where there are manual efforts than can be automated by tool creation.

Title: When should we stop work and make tool?


问:
How should you deal with a popular project that you no longer want to maintain?
I am the maintainer of a project which has a large non-technical userbase. I've been maintaining it for about 4 years now and adding new features as they've been requested.

I'd like to move on to other projects now and stop developing for this application. Because of the non-technical nature of the users, there have been very few code contributions in the past. I don't believe I will be able to find anyone else to take over the project in my stead.

Bugs, issues, feature requests - these are still coming in. I am still responding to emails for help, as I am not sure if I should ignore them, tell them that I'm not working on the application, or if I should respond to emails in only certain cases.

What is the best way to 'abandon' this project, but still let users use the application?

Update (July 2016) - It didn't go as planned.  I made an announcement in the README and soon after, I started receiving contributions of a more substantial nature.  Pull requests with bug fixes, features, documentation, issue activity.  Since then, the project has felt 'reinvigorated' and I'm now happily maintaining it along with newer projects.  I have collaborators as well.  At a guess, it may have been the kind of contributions which were affecting my view of the project and with the quality of contributions improving, it didn't feel like a chore any more.

答:
Do you want to abandon the project because...

you don't want to do it any more ?

Then:  Graceful shutdown ala Reader.

Or ... hire a developer ( continue below)

Or because you are losing money?

Calculate out-of-pocket costs ( and continue below)

Or because you aren't making money?

Calculate how much you need to make for you to feel differently :

out-of-pocket costs must be covered

cost of a developer to continue development

a profit margin

Be honest with your users: explain to them that it costs a certain amount of time, energy, etc. to maintain the service.

Then ask for donations and/or charge for existing features. Do not try to invent premium features that just delays determining if the service is really valuable enough to support itself. Just go with the features you have.

If users bitch well then they can go elsewhere. If not enough donations and/or sign-ups, then shutdown.

Be brutal - once you pull the plug don't look back.


问:
When there is no API
When it is necessary to integrate with a web application, and an API is unavailable, is it a viable solution to simulate a web browser interacting with the web application as a real user would interact with it?

UPDATE

Some context.

Web App belongs to a vendor/partner. Their timeline for building a proper API will not meet our needs.

Scraping for data is the least used part. Full CRUD for interacting with the app is required.

As a developer, I can see that it will work, but I want to be able to address concerns that others may raise about this approach.

Would you base a mission critical business application on this approach? Why or why not?

答:
When there is no API, ask the owner of the website for a suggestion.

For example, let's say you're interested in a list of movies published by a website which collected a large database of nearly every released movie for decades. There is no API.

If you ask the owner:

Maybe he can sell you the raw data,

Maybe there is an API, just not a public one. It is not a rare case: creating an API for internal use is one thing; writing complete documentation, examples, etc. in order to release it to the public is a different story. In such case, giving access to an internal API to a trusted partner may be possible.

Maybe the website doesn't have any database, but simply retrieving the data from a third party web service. The owner can point you to this service in order for you to use it directly.

Maybe the owner is willing to spend some time creating an API.

Maybe the owner is ready to hire you to create the API.

Maybe there is a way to call a simplified version of the website, which will give you the opportunity to you to work on an easy to understand markup and to the owner to see the bandwidth not used excessively.

etc.

There are plenty of opportunities in this case.

If you start scrapping the website without asking any one, sooner or later, the owner will see it. It would be up to him to:

Either change the markup of the web pages to force you to rewrite your entire app. Then change it again. And again.

Or block you.

Or file a claim for copyright violation.

In all those three cases, the consequences would range from slightly annoying to consequent money loss. Don't go this way.

Title: When there is no API


答:
The main difference between corporate programming and college programming is scale.  In school you never get an assignment that one person can't start and finish within a semester.  As a professional you might work with dozens of other programmers on software that lasts for years without being "finished."

At a micro level the work isn't that different.  After all, if it were too different, then a college degree wouldn't be of any value to companies.  But it's sort of like the difference between baking 12 cookies and baking 12,000 cookies.  You can be really good at the former and completely clueless at the latter.

In school you're mainly concerned with making a correct program.  At work your software being correct is not enough.  It has to be maintainable, testable, efficient, and able to be worked on simultaneously by multiple people.  That's something schools try to teach, but you can't really learn it completely except by doing it.

Title: What's the difference between college-level and corporate programming?

Body:
I have just completed my Bachelors degree in IT field. I have deep interest in coding and really want to be a professional in it. Now, apart from college courses, I have been learning programming(C#) on my own (college level programming is too basic). Now I feel I need a little more time to be close to professional programmer. But some of my seniors say that corporate world programming is too different from bookish programming, hence there is no point in wasting time. (They are not programmers themselves, this may be probably what they heard).

Would I benefit by reaching an advance level of C#? or as mediocre level is sufficient to break interviews, higher levels do not matter to firms because they rely on their training purely to teach how things work in corporate world and learning more won't help me much?
Please if there are some professional programmers who can help, I promise this is something which about every student interested in programming want to ask at my stage. "How do you actually change from learner to professional in field of programming?" - keep learning until you are perfect or joining a firm is must once basics are covered?


问:
Create and delay task for 24 hours
I'm trying to come up with a sane architecture to delay a task for 24 hours.  So far I've thought of:

unix cron job, but this will not be able to take the load we give it, since we will have many thousands of delayed tasks per day

Use RabbitMQ with dead letter exchange, however, this is a hack and being a hack is riddled with problems - impossible to monitor without mutilating the messages, etc.

Other solutions I've come up with are poll based, e.g., insert task into MySQL and have a poller responsible

Amazon SQS only supports up to 15 minute delays.  I could write a punt loop for # of delays, btu this is already reinventing the wheel way too much.  Plus using SQS this would get expensive as we pay per message.

Redis possibly...? have not heavily investigated this. I know Memcached is not appropriate as it won't really guarantee persistence that long.

What existing technology is good for this?  I don't want to reinvent the wheel here, given that I'm pretty sure I'm not working on the first software product that requires performing a task tomorrow. Thus far I've been database driving things.

答: I don't have much experience with job scheduling and batch processing, but I do know Quartz is an enterprise level tool that let's you schedule thousands of jobs if needed and it lets you assign system resources (cores/threads), etc. You might want to have a look at it if you are willing to create (or already have) a Java solution.</p>

Title: Create and delay task for 24 hours


问:
Language agnostic programming books
Are there any great programming or software development books that are language agnostic?  Why should I read it?</p>

答:
Test-Driven Development: By Example by Kent Beck.

A super introduction to TDD. Got me started on the TDD path. Code samples are Java, but the material is otherwise very language-agnostic.

Title: Language agnostic programming books


答:
Short answer, yes - the corporate world is quite different than many college environments.

That said, companies know this. We expect college graduates to be nearly useless. If you have spent time on your own learning to program, that's great. You don't need to be super awesome to apply, but understand that staying mediocre will not cut it.

You won't learn a lot of what you need in business on your own. Apply as soon as possible while continuing to learn on your own.


问:
Is it considered a bad practice to add logic in a property setter?
I jumped in to a project and I see that the other developers are adding a lot of logic in the setters of synthesized properties.
I understand how this works, but I think that it makes it hard to understand the flow of the program; while reading the code, whenever I see self.something = whatever, I always check if something's setter is overridden.

What are your opinions around this topic? Do you think this is a sign of bad architecture or an elaborate solution?

I would be glad to read more on this if you have relevant links/sources, it's just too hard to get good google results so I decided to ask here as well.

Thanks for any answer and please note that I'm talking about objective C in case you haven't seen the tag (even though this shouldn't be a language specific issue I guess).

答: Setters are typically used to change the state of an object with no significant side effects or heavy calculations;use methods and functions for that. The primary reason for setter implementation is changing and maintaining a valid state. So, limiting range, setting flags to request recalculation, or adjusting related properties is absolutely fine.


答:
Is it considered a bad practice to add logic in a property setter?

No

Properties were invented to allow class designers to have logic attached to a convenient interface of field access and assignment.

How much is too much?  It depends on the responsibilities of the class.  Here are some things that are reasonable to put in a property setter:

update some derived values

notify observers that the class state has changed

propagate the change to some contained object

propagate the change to a backing store

perform validation

Programming is easier when classes have interfaces that make it obvious what the class can do, without making callers think about how it is being done.  Putting logic behind property setters allows classes to hide their implementation behind a simple interface.  For some classes, no methods are required.  Just turn the knobs by setting properties and read the output by getting properties.

Body:
I jumped in to a project and I see that the other developers are adding a lot of logic in the setters of synthesized properties.
I understand how this works, but I think that it makes it hard to understand the flow of the program; while reading the code, whenever I see self.something = whatever, I always check if something's setter is overridden.

What are your opinions around this topic? Do you think this is a sign of bad architecture or an elaborate solution?

I would be glad to read more on this if you have relevant links/sources, it's just too hard to get good google results so I decided to ask here as well.

Thanks for any answer and please note that I'm talking about objective C in case you haven't seen the tag (even though this shouldn't be a language specific issue I guess).


答:
I don't know about objective C, but as you say, it seems a generic enough question for any OO language. First of all and actually related to that, whether to have setters and getters in the first place is a matter of discussion (in some cases their existence is justified by the use of a framework or library).

I believe that the name of the method should explain what the method does and all the method does. Additionally the documentation associated to that method should describe it in a more explicit way. In this sense a method name in the form "set" + {noun} shouldn't have any side effects other than setting the value of a variable and that should be the only action associated to it. Checking that the argument is valid, is acceptable but it should be described in its documentation.

Title: Is it considered a bad practice to add logic in a property setter?


答:
There are many differences between programming in school and in the real world. I'm not sure there is such a thing as corporate programming.

Depending on where you're actually working, there will be huge differences. There will also be huge differences depending on the tasks at hand.

However there are still some common issues.

the real world code life-cycle is very different from college homework. In real world programming you are usually working on some existing code base. One of the biggest issues is to avoid breaking compatibility with code used by your customers (who may be internal customers or external customers, depending on your actual workplace and case). The code you are writing will also probably be used for years afterward (this depends: the issue is not the same for a web site or code embedded in some devices). If you want to get ready for this, get in the habit of writing unit tests and functional tests for every piece of code. That is not always done with real world code, but it should make your life simpler both in college and in the corporate world.

design/requirements are usually much fuzzier in the real world than in a collegiate atmosphere. When writing professional code, someone has to define the code's purpose, and you aren't simply given toy problems or even well known problems. It is very likely that sooner or later it will be you who is doing the designing! Customers usually don't know what they want (and even when they know what they want it may not be what they need), and managers usually just describe the large picture, leaving many details and choices to the programmers. Depending on the methods followed ("agile" -vs- "V cycle", etc.), choices and detailed problem definition may occur sooner or later, but you should at least keep an open mind and wonder if you're actually doing what is required. You may also consider changing requirements if the ongoing task is too hard to code or is inefficient. You may end up writing something useless or overly complicated anyway because the customer or your manager didn't get your point or they disagree with you. Still, you should always question requirements (it's a survival skill). Also keep in mind that requirements may change in the middle of a task, and you should be ready for that.

in college when you get an assignment you are usually supposed to write some code. In the real world, you usually start by checking if you can use existing code instead: reuse or change parts of a project, use or buy libraries, etc. If you find existing code that fits the assignment, you may end-up using it or not (there may be maintenance issues, performance issues, copyright issues, or even pricing issues), but the option of reusing existing code should usually be considered.

There are obviously many other issues related to teamwork, project scale, etc. But the above points are issues you are very likely to see in corporate environments but do not have to consider in your college assignments.


问:
Is the Observer pattern adequate for this kind of scenario?
I'm creating a simple game development framework with Ruby.

There is a node system. A node is a game entity, and it has position. It can have children nodes (and one parent node). Children are always drawn relatively to their parent.

Nodes have a @position field. Anyone can modify it. When such position is modified, the node must update its children accordingly to properly draw them relatively to it.

@position contains a Point instance (a class with x and y properties, plus some other useful methods).

I need to know when a node's @position's state changes, so I can tell the node to update its children.

This is easy if the programmer does something like this:

```<code>@node.position = Point.new(300,300)
</code>```

Because it is equivalent to calling this:

```<code># Code in the Node class
def position=(newValue)
  @position = newValue
  update_my_children    # <--- I know that the position changed
end
</code>```

But, I'm lost when this happens:

```<code>@node.position.x = 300
</code>```

The only one that knows that the position changed is the Point instance stored in the @position property of the node. But I need the node to be notified!

It was at this point that I considered the Observer pattern. Basically, Point is now observable.

When a node's position property is given a new Point instance (through the assignment operator), it will stop observing the previous Point it had (if any), and start observing the new one. When a Point instance gets a state change, all observers (the node owning it) will be notified, so now my node can update its children when the position changes.

A problem is when this happens:

```<code>@someNode.position = @anotherNode.position
</code>```

This means that two nodes are observing the same point. If I change one of the node's position, the other would change as well. To fix this, when a position is assigned, I plan to create a new Point instance, copy the passed argument's x and y, and store my newly created point instead of storing the passed one.

Another problem I fear is this:

```<code>somePoint = @node.position
somePoint.x = 500
</code>```

This would, technically, modify @node's position. I'm not sure if anyone would be expecting that behavior. I'm under the impression that people see Point as some kind of primitive rather than an actual object.

Is this approach even reasonable? Reasons I'm feeling skeptical:

I've heard that the Observer pattern should be used with, well, many observers. Technically, in this scenario there is only one observer at a time.

When assigning a node's position as another's (@someNode.position = @anotherNode.position), where I create a whole new instance rather than storing the passed point, it feels hackish, or even inefficient.

答:
I think you're missing the observer (subscribe) side of the Observer pattern. Take a look at the Observable module.

You could create an ObservablePosition class that manages a node's Position (getters, setters, etc.) and notifies observers as needed. Child nodes would subscribe to changes on their parent's OP. This would have the desired affect of automatically cascading a node change to all children in the tree below it. This design could also be generalized to allow child nodes to listen for changes on multiple node properties.


问:
I have only two languages on my resume - how bad is this?
I have a question that can be best answered here, given the vast experience some of you guys have!

I am going to finish my bachelor's degree in CS and let's face it, I am just comfortable with C++ and Python. C++ - I have no experience to show for and I can't quote the C++ standard like some of the guys on SO do but yet I am comfortable with the language basics and the stuff that mostly matters. With Python, I have demonstrated work experience with a good company, so I can safely put that.

I have never touched C, though I have been meaning to do it now. So I cannot write C on my resume because I have not done it ever. Sure I can finish K & R and get a sense of the language in a month, but I don't feel like writing it cause that would be being unfaithful to myself.

So the big question is, are two languages on a a resume considered OK or that is usually a bad sign? Most resumes I have seen mention lots of languages and hence my question. Under the language section of my resume, I just mention: C++ and Python and that kinda looks empty!

What are your views on this and what do you feel about such a situation?

PS: I really don't want to write every single library or API I am familiar with. Or should I?

答:
It depends on what kind of job you are trying to get, really, as well as who is doing the choosing.

Personally, were I hiring a junior coder, I'd look mostly for mindset and only expect them to know a language or two.  Were I hiring a lead coder, I'd want to see a laundry list of languages, as those who haven't worked in many languages invariably have no clue about language design, and it is my personal philosophy that someone who understands at least the basics of language design is a much better big picture sort of coder.


答: Why not have a separate class or method responsible for updating the node and its children with the new values. You can have it return the new value to update your reference with and then it is a just simple calculation. If you go that route, you don't have to worry about knowing who is subscribed to who and all of that stateful mess.</p>

Title: Is the Observer pattern adequate for this kind of scenario?

Body:
I'm creating a simple game development framework with Ruby.

There is a node system. A node is a game entity, and it has position. It can have children nodes (and one parent node). Children are always drawn relatively to their parent.

Nodes have a @position field. Anyone can modify it. When such position is modified, the node must update its children accordingly to properly draw them relatively to it.

@position contains a Point instance (a class with x and y properties, plus some other useful methods).

I need to know when a node's @position's state changes, so I can tell the node to update its children.

This is easy if the programmer does something like this:

```<code>@node.position = Point.new(300,300)
</code>```

Because it is equivalent to calling this:

```<code># Code in the Node class
def position=(newValue)
  @position = newValue
  update_my_children    # <--- I know that the position changed
end
</code>```

But, I'm lost when this happens:

```<code>@node.position.x = 300
</code>```

The only one that knows that the position changed is the Point instance stored in the @position property of the node. But I need the node to be notified!

It was at this point that I considered the Observer pattern. Basically, Point is now observable.

When a node's position property is given a new Point instance (through the assignment operator), it will stop observing the previous Point it had (if any), and start observing the new one. When a Point instance gets a state change, all observers (the node owning it) will be notified, so now my node can update its children when the position changes.

A problem is when this happens:

```<code>@someNode.position = @anotherNode.position
</code>```

This means that two nodes are observing the same point. If I change one of the node's position, the other would change as well. To fix this, when a position is assigned, I plan to create a new Point instance, copy the passed argument's x and y, and store my newly created point instead of storing the passed one.

Another problem I fear is this:

```<code>somePoint = @node.position
somePoint.x = 500
</code>```

This would, technically, modify @node's position. I'm not sure if anyone would be expecting that behavior. I'm under the impression that people see Point as some kind of primitive rather than an actual object.

Is this approach even reasonable? Reasons I'm feeling skeptical:

I've heard that the Observer pattern should be used with, well, many observers. Technically, in this scenario there is only one observer at a time.

When assigning a node's position as another's (@someNode.position = @anotherNode.position), where I create a whole new instance rather than storing the passed point, it feels hackish, or even inefficient.


答: The main thing you need for doing well in corporate programming is patience and the ability to communicate with users that don't understand technology.  Make sure you use unit testing, version control, carefully debug and use proper tracing/logging.   The languages may change, but staying calm and carefully looking for issues will always work.   </p>


答:
I believe your first instinct is the best one - in that it is where you should look for the answer.  The early versions of cron was a polling approach (every minute, check to see if anything should be run).  A later version made use of a discrete event simulator.  The article that lead to this version of cron is titled "An efficient data structure for the simulation event set".  Reading this (it is several pages long) may help you in understanding of the algorithm and how to reimplement it yourself.

At any given time, you know all of the events that will happen within the next 24 hours.  Each time the process runs to deal with something, it looks at the head of the queue to see how long it needs to sleep - it then sleeps that long, and launches another thread or process to deal with that job, and repeats (read the head, sleep, fork, read head, ...).

Internally, this is how cron works.

The question then becomes how do you want to update and persist this data structure.  Writing the data to a database or to a file on a file system seem to be the two best approaches for this - being ways that are simple to access from a multitude of different approaches.

I would not try to persist the data in a message queue as it really isn't meant for that.

Title: Create and delay task for 24 hours

Body:
I'm trying to come up with a sane architecture to delay a task for 24 hours.  So far I've thought of:

unix cron job, but this will not be able to take the load we give it, since we will have many thousands of delayed tasks per day

Use RabbitMQ with dead letter exchange, however, this is a hack and being a hack is riddled with problems - impossible to monitor without mutilating the messages, etc.

Other solutions I've come up with are poll based, e.g., insert task into MySQL and have a poller responsible

Amazon SQS only supports up to 15 minute delays.  I could write a punt loop for # of delays, btu this is already reinventing the wheel way too much.  Plus using SQS this would get expensive as we pay per message.

Redis possibly...? have not heavily investigated this. I know Memcached is not appropriate as it won't really guarantee persistence that long.

What existing technology is good for this?  I don't want to reinvent the wheel here, given that I'm pretty sure I'm not working on the first software product that requires performing a task tomorrow. Thus far I've been database driving things.


问:
How to provide a ubiquitous object without including it in every parameter list
I'm writing a small C++ class, Block, to transform serialized data into a memory structure, and supply the structured data to callers through several accessor methods.  I've tried to keep its scope specific and limited.  The users of the class are very low-level - they, too, are very narrow in their focus and have as few external dependencies as possible.

This is how I've been taught to engineer things if at all possible.  By minimizing dependencies and creeping featurism, it's easier to unit test, and easier to reuse.

The problem is that my class depends upon someone else's class, Metadata.  It, too, does one very specific thing: it reads data that defines the characteristics of the data stream I'll be transforming from a database table and passes it to me.  His class checks for mySQL errors, which should be rare, and logs any errors to a Log object.

This Log object appears in all of our company's applications.  Instantiating it is a big deal - it wants Job numbers, it wants a lot of configuration information from the database that's normally put there in production by account managers using a GUI.  You have to do a lot of work before your program can instantiate the Log.  Yet this tiny, low-level class (Metadata) with one tiny task wants it to be passed in, by me.  My object certainly has no business instantiating the Log, so I have to take it as a parameter from whoever calls me.  And so forth, up the calling hierarchy.

I can understand why management wants a class to encapsulate and standardize message logging.  But the need for it to be passed to, and through, just about every method is extremely ugly, and makes testing and reuse much more difficult.

This kind of problem must be fairly common.  How can this be done without cluttering up the signature of every method you write?  Is this a legitimate case for Globals?  Is there some kind of Object Oriented approach?  And, is this a God object?

答:
The mainstream way of dealing with a "global" logging object would be to use Dependency Injection.

The slightly less mainstream way would be to use Aspect Oriented Programming.

The interesting solution is to reframe logging as an instance of the Writer Monad. Here's an example in Scala: http://blog.tmorris.net/posts/the-writer-monad-using-scala-example/. Note: the concept is language-agnostic, Scala is simply used as a convenient notation here.


答: I'd say the fundamental difference between corporate vs. college level programming is corporate level programming is much more of a collaborative process than what you will encounter in a class setting and the emphasis is much more on product development than pedagogical learning.</p>


答:
If you are really expecting that the corporate world programming will be advanced high level programming culture, I think you will rather disappointed. Programming in the corporate world is more about being able to take responsibility for the code that you write and keeping it maintainable.

But to your question

How do you actually change from learner to professional in field of programming?

This has nothing to do with corporate and college level programming but programming in general.
If you really want to learn start building your own software, something you want to build or start working in open source software projects. Ask questions that you face. And read other people's code.


问:
How to justify migration from Java 6 to Java 7?
We were migrating from Java 6 to Java 7. The project is behind schedule and risks being dropped, in which case it will continue to use Java 6.

What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that  I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, Java 2D/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use.

[I am going through many sites like Oracle adoption guide, bug database, questions on Stack Overflow].

Update: Thanks for the answers.  We rescheduled the update to next release.  Closest we got was security.  Accepting the highest voted answer.

答:
In general, there are a number of fairly broad changes to make things easier on the programmer. Your manager might not care too much about such things, but making programmers spend less time thinking about boilerplate code, and thus have more time to think about the actual goal of what they're implementing, should increase efficiency, decrease bugs, etc., which can be a very powerful argument. Oracle has a fairly extensive list of changes, but it's rather lengthy, so I'll summarize as much as possible.

Language features include:

Less boilerplate on Generics. The code Map<String, String> myMap = new HashMap<String, String>(); can be reduced to Map<String, String> myMap = new HashMap<>(). The compiler can infer the Generic types needed on the right side from the left, so your code gets a little shorter and quicker to read.

Strings work in switch statements now, using the semantics of the .equals() method instead of ==.

Automatic resource management using try-with-resources. This makes code cleaner, but also has an advantage over old-style try/finally-based code. If an exception is thrown in the try statement,  and then another is thrown while closing, code which uses traditional try/finally statements will completely lose the original exception, and only pass up the one which was thrown in the finally block. In a try-with-resources statement, the runtime will suppress the exception that the close() calls threw, and bubble the original exception up the stack, under the assumption that this original exception is the one that caused all the problems in the first place. Additionally, instead of abandoning the other exception to the garbage collector, this suppression allows the close-thrown exceptions to be retrieved using Throwable.getSuppressed.

Numeric literals can be made easier to read. All numeric literals allow underscores, so things like int n = 1000000000 can be made into a much more readable int n = 1_000_000_000, which is much easier to parse as being one billion, and harder to type wrongly without noticing. Also, binary literals are allowed in the form 0b10110101, making code that works with bit-fields a little nicer to read.

Handling multiple exception types int the same catch statement can be done, reducing duplicating code, and potentially making it easier to refactor later.

Every one of these changes is something your manager might not directly care about, but they make it a little bit easier to write correct code without as much effort and thought, freeing your mind to focus a little more on the actual logic you're trying to implement, and they also make it a little easier to read code later, making debugging a little faster.

On the API side, a number of API updates have also occurred:

Security-wise, several encryption methods have been added/deprecated, as crypto moves ever forward.

File IO has been changed, (this might be a better link, though ) adding some better abstraction in a number of places. I haven't personally dived into the new IO stuff, but it looks like a very useful overhaul, making it much easier to work with the filesystem without quite as much pain.

Unicode Support is up to Unicode 6.0, along with a number of other internationalization enhancements.

Java2D, which you mentioned in your question, has been improved. Better Linux font support, better X11 rendering on modern machines, and handling of Tibetan scripts.


问:
Serializing an object in different ways
It is usual for me, when doing web development, to copy attributes from my model classes to the other class that will be sent to the client. Usually, with a class that accepts a model and extracts the necessary information this is sufficient (something like a adapter I suppose), but sometimes it is not that easy.

In some systems, for different reasons I need to send a different sets of attributes, and this is where simplicity seems to disappears.

With my usual approach I end up with lot's of classes very similar one from each other, just because one is for being used in one channel that requires some information and the others for channels that require very similar information. But cannot be the same sum of the two because performance or security. (When I say channels it is because it could be a serialized using json or xml, or used in other protocols, or just displayed as html by the server.)

The question is: Is there a pattern that allows for different transformations of a object (that might aggregate others objects) depending the context being used? (without too much code duplication)

Case of study: in a distributed cards game (like poker), I need to send to every user the score, the name of the players, the cards that were played, and the cards he has in his hand. But when the game ends I need to send the cards in the hands of the others players too. And in other view of the game I need to send only the score and the name of the players.

Sorry about my English, it is not my first language (and the idea I am trying to communicate seems a little complex for me).

答:
This might be solveable with the use of different design patterns. This will lead to a generic approach, but it might be not so effiecient and easy to understand.

For serializing you can use Memento. If you want to serialize depending on some state or so you can use State or Strategy.

Deserializing should be working the same way.

Maybe it is also sufficient to send an enum (int) that determines the object state.

Title: Serializing an object in different ways


答:
What you are doing right now is the Data Transfer Pattern. </p>

<p>You might want take a look at 'composition' (Robert Martin). It's not really a pattern but rather a guideline. </p>

Title: Serializing an object in different ways

Body:
It is usual for me, when doing web development, to copy attributes from my model classes to the other class that will be sent to the client. Usually, with a class that accepts a model and extracts the necessary information this is sufficient (something like a adapter I suppose), but sometimes it is not that easy.

In some systems, for different reasons I need to send a different sets of attributes, and this is where simplicity seems to disappears.

With my usual approach I end up with lot's of classes very similar one from each other, just because one is for being used in one channel that requires some information and the others for channels that require very similar information. But cannot be the same sum of the two because performance or security. (When I say channels it is because it could be a serialized using json or xml, or used in other protocols, or just displayed as html by the server.)

The question is: Is there a pattern that allows for different transformations of a object (that might aggregate others objects) depending the context being used? (without too much code duplication)

Case of study: in a distributed cards game (like poker), I need to send to every user the score, the name of the players, the cards that were played, and the cards he has in his hand. But when the game ends I need to send the cards in the hands of the others players too. And in other view of the game I need to send only the score and the name of the players.

Sorry about my English, it is not my first language (and the idea I am trying to communicate seems a little complex for me).

Body:
What you are doing right now is the Data Transfer Pattern.

You might want take a look at 'composition' (Robert Martin). It's not really a pattern but rather a guideline.


问:
Why don't companies ship multiple modules within a mobile app? Are there concerns about tight coupling?
Preface: My question does not exclusively pertain to Google and it doesn't exclusively pertain to iOS. I'm only using Google and iOS as examples because they are familiar to many. I could have just as easily used 'Company X', apps 'A', 'B', 'C', 'D', and 'E', and 'Android', but I wanted to keep my question rooted in the real world with a tangible example.

In the iOS app store, Google has many apps. At a glance, I can see 'Google Search', 'Google+', 'Google Maps', 'Google Earth', and 'Gmail'.

But I wonder - Why didn't Google simply create a 'Google' app which can provide all of the functionality that these five apps provide? The black menu bar at the top of each Google webpage makes this possible on the web; so why don't they make this possible by way of a menu button at the bottom of one "global" Google app?

Is Google concerned about tight coupling between the apps?

Is Google concerned about tight coupling between the teams that develop the apps?

Is Google concerned about app size?

Is Google concerned about the memory footprint or CPU load that such a monolithic app might incur when it is loaded?

[Not a rant. Merely playing devil's advocate.]

In spite of many advantages, some iOS critics say that multiple pages of apps leave the iPhone and the iPad feeling "cluttered". This is particularly relevant to my question because it seems a bit much to expect a user to know about (and manage) so many Google mobile offerings. From a product standpoint, and arguably a usability standpoint, it seems like it would be wise to ship a single app.

If you're curious, I own an iPhone and a Nexus 7; so I'm not wedded to either of the two major mobile platforms.

And I have a real problem to solve here - Whether to bundle multiple apps inside of one large app, or to distribute separate bits of functionality in multiple apps.

EDIT: In response, to @MichaelT's comment

While there is indeed a 2GB size limit for apps, the size of your sandbox is only limited by the remaining capacity on the device.

答:
Users expect a mobile app to perform a single task, or a small set of very related tasks.

The mobile platforms that you mention started particularly as phone OS's. Typically users performs many short tasks on their smartphone throughout the day. This is totally different from desktop computers. This short bursted usage pattern has lead to the design of a customizable home screen that gives direct access to single-task apps. Third party developers were also encouraged to focus their app around a single task.

With the arrival of tablets, the mobile device usage patterns have diversified, but the vendors apparently chose to keep the paradigms that were originally optimized for phone users. I suppose because users have become familiar with it.

To go back to your example of Google apps: most people won't need all of them. And even though it is true that the home screen clutter can make it harder to find the right app/task; an app with an extra level of navigation is pretty much the same.


答:
Karl's answer about scale is spot on. You don't get to sort an array of 15 numbers, you'll have to sort data set of a million ,say, account numbers.

A data structures and algorithms class will probably tell you a dozen different ways to sort. In a real application you are likely to throw in a order by clause and let the database optimize it.

As for getting prepared for the corporate world there are two ways I would suggest
a) Get an internship even a low paid or no-pay one will let you watch others work.
b) With all the app stores around you could try to write and publish an app to Apple/Google/MS stores. This will help you understand workflows better, the value of testing, the need to setup the right environment and tools and more.


答:
beside the excellent answer provided "corporate programming" is also about requirements that are not clear or change.

What would you do if your professor changes the requirements of your programming homework two days before you have to deliver it?

In industry this quite common.


问:
What makes JVM so much versatile to support so many JVM languages?
JVM supports so many languages other than Java like Groovy,Clojure,Scala etc which are functional languages unlike Java(I am referring to Java before Version 8 where Lambda's are not supported) that doesn't support functional capabilities.On a high level what makes the JVM so versatile that it can support both Object Oriented as well as Functional languages?

答:
The JVM was written to basically act like a CPU, there is a set of instructions, kind of like assembly, that the VM runs called bytecodes. If you can write a compiler that generates a valid set of bytecodes, then the JVM can run them.

Wikipedia has a list of the bytecodes:

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

as well as an explanation of how the JVM loads the byte codes:

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

By using the invoke style bytecodes, a functional language can execute code, regardless of what the source looks like. Also, with the addition of invokevirtual, language implementations like jruby have been giving some flexibility with how they run.


问:
Data integrity in NoSQL situations
Background

To start off, at work I work with a legacy system that, in its day, was quite spectacular, but now is ...interesting... to work with. It uses IBM (now Rocket) UniVerse as its backing database. One particular part of it that has caused some issues is its lack of data-integrity checks. By data integrity, I don't mean file corruption, but rather things like orphaned records or invalid keys. The particular version they use doesn't support things like triggers and such and so unless the programmer remembered to update their computed indexes, it becomes "broken" and filled with bad data. Now, the other programs have been built to live with this bad data, but it is most annoying when putting it into another database, such as MySQL (using InnoDB as the engine) which actually has constraints on the data.

The question

I'm experimenting with MongoDB and NodeJS just to see what all the hype is about. I really like Mongoose as well and its schema system. I've been reading a lot about what to store on each record vs in a separate collection. Perhaps its just my own RDBMS bias, but I decided to store each "type" of thing in a separate collection and utilize Mongoose's "populate" functionality to essentially relate the records together. Now, I am sure someone is going to say that that is going against the whole NoSQL thing, but I haven't really read anywhere that says that just because something stores documents instead of records and has no set schema on the db level that it can't be made relational.

In my experiment, I have "Posts" and "Comments". I see four ways to store the relation between these two:

The full data for each comment is put directly onto the post as a subdocument. There are two main cons that I have seen with this: If I decide to put comments on something else (let say a "Page") as well, I have to essentially repeat myself and it isn't quite as simple to find out how many comments a user has posted if the comments are actually stored in several collections

Comments are a separate collection and they store their parent's key and a Schema name for mongoose to use when populating (the schema name switching wouldn't be automatic). This isn't too bad, but its biased towards loading comments first and posts later. Finding out the comments on a post isn't hard, but requires a manual query.

Comments are a separate collection and posts have a list of comment ids that relate to them. This is biased towards loading posts first and finding out what a comment is attached to becomes difficult. However, mongoose would let me load the comments without having to write anything additional.

Comments are a separate collection and have a parent id. Posts also have a list of comment ids. This combines the above two methods and neutralizes their cons and makes for relatively few "manual" queries, but introduces the possibility of data becoming dirty and out of sync like the legacy system that I described above (e.g. a comment says it belongs to one post and another post (or multiple posts) claims that they own that comment).

I was going down the latter path listed above and I realized that I was starting to enter the realm of this legacy system that had caused so many headaches with its manually updated indexes and possibility for bad data.

Now, I don't expect to do a ton with this little experiment of mine, but its the principal of the thing that has me thinking. What would you all recommend to go with on this? I want to be able to keep query counts low, but I also don't want to have to remember to update all these indexes. There has to be a happy medium somewhere.

Another option, of course, is to just use MySQL with some nice schema constraints, but that isn't the point of this particular exercise for me since I've done that tons of times already.

答:
my experience on using node.js with NoSQL resulted in skipping Mongoose and using the node-mongodb-native driver.

Reasons for this is that Mongoose actually conflicts with the node.js way of doing things, this means building your own need-framework by gluing up different tools together. Mongoose looks great if you come from a traditional environment but you will notice quick limitations of things which just go complicated. Better use the native driver and if necessary create a customer helper manager for specific collections.

Regarding your origin question I would recommend you to take the first concept and put everything in one document. I know that in the beginning it sounds silly as you feel wasting resources. This is something we have learned from data modeling table structures in MySQL. This all is not necessary with document-orientated DBs. Their idea is making things as simple as possible and just store the document you take. Believe me everything else is just waste of time. When I look back how much time I wasted just trying to build a REST API which supports Mongoose populating...

As conclusion I would recommend to just think about document orientated databases as just a persistence for serialized objects and as long as you do not plan any complicated queries or you plan to have data only once in order to keep it up-to-data avoid wasting your time with trying to rebuilt MySQL.

Hope it helps you.

Title: Data integrity in NoSQL situations


答:
Compared to other VMs, the JVM actually isn't particularly versatile. It directly supports statically typed OO. For everything else, you have to see what parts you can use, and how you can build everything else your language needs on top of those parts.

For example, until Java 7 introduced the invokedynamic bytecode, it was very hard to implement a dynamically typed OO language on the JVM - you had to use complex workarounds that were bad for performance and resulted in horribly bloated stack traces.

And yet, a bunch of dynamic languages (Groovy, Jython, JRuby among others) were implemented on the JVM before that.

Not because the JVM is so versatile, but because it is so widespread, and because it has very mature, well-supported and high-performing implementations.

And, perhaps even more important, because there is a huge amount of Java code out there doing pretty much anything, and if your language runs on the JVM, you can easily offer facilities to integrate with that code. Basically, having your language run on the JVM is the 21st century version of offering interoperability with C.

Title: What makes JVM so much versatile to support so many JVM languages?

Body: JVM supports so many languages other than Java like Groovy,Clojure,Scala etc which are functional languages unlike Java(I am referring to Java before Version 8 where Lambda's are not supported) that doesn't support functional capabilities.On a high level what makes the JVM so versatile that it can support both Object Oriented as well as Functional languages?


问:
NodeJS: Freeze dependences before testing and deployment? Check in node_modules?
Suppose you have a NodeJS application.
A release could consists of multiple steps:

Automated and/or manual tests

Deployment

(if something goes wrong) Rollback to the last stable version

There are some  desirable requirements regarding the application's dependencies:

When you have done your testing, you want to deploy exactly the version that you tested with, including all dependencies.

The same goes for rollbacks: You want to restore not only your own code, but all external dependencies, too.

My question is about best practices to meet this goals.

What is the recommended way to create a snapshot of all dependencies of your NodeJS application?

Here are three options that I can think of:

In this article, the author recommends to put the node_modules directory under source control. (Not for all modules, but only for modules that will be deployed.)

One alternative, which the same article describes as an anti-pattern, is to use explicit version locking. His argument seems reasonable: When you lock, for example, Express to a certain version, you still cannot control that one of its dependences hasn't introduced a subtile bug, later.

Just don't care and always use the most recent version of all external modules.

My thoughts so far (but I don't have much experience with NodeJS yet):

3) seems to be too reckless.

I tend to 1), but I'm not sure where to put the node_modules. When you just check it along with your normal code, I fear that workflows like npm link to your local modules will no longer work. Additionally, there is always the problem of annoying merge conflicts.

答:
I do not understand your nead of a node_modules version control. I mean you can easily define which version the dependency should have:</p>

```<code>{
    "name": "native-gpio",

    "version": "0.0.6",

    "description": "sysfs GPIO wrapper for node.js",

    "author": "Bodo Kaiser <i@bodokaiser.io>",

    "license": "MIT",

    "keywords": ["gpio", "addon"],

    "main": "lib/index.js",

    "gypfile": true,

    "scripts": {
        "test": "make test",
        "install": "make install"
    },

    "dependencies": {
        "node-gyp": "0.10.6"
    },

    "devDependencies": {
        "mocha": "1.12.0",
        "chai": "1.7.2"
    },

    "repository": {
        "type": "git",
        "url": "git://github.com/bodokaiser/node-native-gpio.git"
    },

    "bugs": {
        "url": "https://github.com/bodokaiser/node-native-gpio/issues"
    }
}
</code>```

Body:
I do not understand your nead of a node_modules version control. I mean you can easily define which version the dependency should have:

{
    "name": "native-gpio",

    "version": "0.0.6",

    "description": "sysfs GPIO wrapper for node.js",

    "author": "Bodo Kaiser <i@bodokaiser.io>",

    "license": "MIT",

    "keywords": ["gpio", "addon"],

    "main": "lib/index.js",

    "gypfile": true,

    "scripts": {
        "test": "make test",
        "install": "make install"
    },

    "dependencies": {
        "node-gyp": "0.10.6"
    },

    "devDependencies": {
        "mocha": "1.12.0",
        "chai": "1.7.2"
    },

    "repository": {
        "type": "git",
        "url": "git://github.com/bodokaiser/node-native-gpio.git"
    },

    "bugs": {
        "url": "https://github.com/bodokaiser/node-native-gpio/issues"
    }
}


答:
The key element in this is the separation of the compilation from the execution phase. By this it is possible to write other compilers compiling other languages to bytecode.

Bytecode there acts similar to machine code of a CPU - you have all the little operations needed to run a program - you can get a variable, do math on it, have conditional operations etc.

Java also isn't special. In Java the existance of multiple languages wasn't even a design goal, unlike other VMs. For Microsoft's .Net CIL the ability to run multiple languages (C#, VB.Net, ...) was a key design element, also the ParrotVM from the Perl6 project aimed to be a generic VM.

For the fun of it I once created a proof that even PHP's Zend Engine would allow that.

And frankly this isn't anything new - even on real hardware you can run multiple languages - i.e. C or Fortran.

The difference to this separation from compilation and execution are clssic interpreters, like some forms of Basic, shell scripts, etc. they often work in a way that they execute code more or less in a line by line way without bringing it in an immediate form in between.


答:
Well going over to pure paid will kill off a lot of users, but there are a lot of alternatives to pure paid. A video game I play gives donators some extra perks like more downloads per hour "a pure skill based game, not to confuse with pay to win garbage lol". Another game Path of Exile offers cosmetic upgrades. Other sites put surveys in exchange for bandwidth. Donation coder gives free users a licenses for (X Time) renewable many times as they want, but donators get a permanent licenses.

There are tons of options offer it for cash but still keep the free users around as well.

Most people have no problem supporting something they like so honestly I'd just try asking first by setting up a tip area calculated to cover your monthly cost.

Title: How should you deal with a popular project that you no longer want to maintain?

Body:
I am the maintainer of a project which has a large non-technical userbase. I've been maintaining it for about 4 years now and adding new features as they've been requested.

I'd like to move on to other projects now and stop developing for this application. Because of the non-technical nature of the users, there have been very few code contributions in the past. I don't believe I will be able to find anyone else to take over the project in my stead.

Bugs, issues, feature requests - these are still coming in. I am still responding to emails for help, as I am not sure if I should ignore them, tell them that I'm not working on the application, or if I should respond to emails in only certain cases.

What is the best way to 'abandon' this project, but still let users use the application?

Update (July 2016) - It didn't go as planned.  I made an announcement in the README and soon after, I started receiving contributions of a more substantial nature.  Pull requests with bug fixes, features, documentation, issue activity.  Since then, the project has felt 'reinvigorated' and I'm now happily maintaining it along with newer projects.  I have collaborators as well.  At a guess, it may have been the kind of contributions which were affecting my view of the project and with the quality of contributions improving, it didn't feel like a chore any more.


答:
Would I benefit by reaching an advance level of C#?

No. We expect students to be useless for several months while we break them in. The degree is just table stakes. Your enthusiasm to learn and follow instructions are your best assets. When interviewing college grads I want a team player that fits in not a hotshot disrupting the group.

...higher levels do not matter to firms because they rely on their training purely to teach how things work in corporate world and learning more won't help me much?

This different for every company but in general larger companies will have a more structured training. This is your first big decision, do you like formal training and a high degree of structure? If so, seek jobs that provide that.

How do you actually change from learner to professional in field of programming?

You change from a student to a pro by getting a job. I recommend Seniors get a co-op with a company through your school. The is be single best way to get your feet wet and get past anxiety of a new profession.

Keep learning until you are perfect or joining a firm is must once basics are covered?

Get a job, don't wait. It is common to be nervous, but be honest about your skills and don't hide your enthusiasm to learn more. It is common to switch companies several times, especially early in your career.

Congrats on finishing your degree and good luck on your journey to professional programming.


问:
Bin sorting problem - Please help categorize
I have a problem I am developing a solution for and currently I solve it with a brute force solution that checks all possibilities. It works for small numbers of bins but I'd like to work with a reasonable speed for increasing numbers, however the algorithm I use (brute force) increases in computing time in a factorial manner related to the number of bins. In other words it gets way too slow pretty quickly after about 6 or 7 bins. I'd like to classify the problem to see if it is NP-Complete, NP-Hard or other so I know where to look in attempting to optimize.

The basic problem is this.

You have a number of points n and you have weights for these points. The points also have an ordering such that points in a bin must be consecutive. You must place these into a total of a maximum of k bins. The bins contain an estimate for the set of points placed in it and the total error of the absolute value of difference in the points and the estimate must be minimized. The goal is to find how to place these points in the bins to have the minimal total error.

Thanks!

答:
Just an idea: randomly swap items in bins, something like this:

```<code>using System;
using System.Linq;
using System.Collections.Generic;

namespace BinsGenetic
{
    class Program
    {
        private const int NumberOfBins = 10;
        private const int NumberOfPoints = 100000;
        private const int MinimalPoint = 1;
        private const int MaximalPoint = 1000;
        private const int NumberOfSwaps = 10000;

        static void Main()
        {
            // Generate empty bins.
            var bins = new List<Bin>();
            for (int i = 0; i < NumberOfBins; i++)
            {
                bins.Add(new Bin(i + 1));
            }

            // Generate 100 points with weight from 1 to 10.
            var points = new List<int>();
            var rnd = new Random();
            for (int i = 0; i < NumberOfPoints; i++)
            {
                points.Add(rnd.Next(MinimalPoint, MaximalPoint));
            }

            // Insert points into bins by random order.
            int c = 0;
            foreach (var point in points.OrderBy(p => p))
            {
                bins[c].Add(point);
                c++;
                if (c % NumberOfBins == 0) c = 0;
            }

            Console.WriteLine("Initial:");
            Test(bins);

            // Get max and min bin.
            for (int i = 0; i < NumberOfSwaps; i++)
            {
                var b1 = bins[rnd.Next(0, NumberOfBins)];
                var b2 = bins[rnd.Next(0, NumberOfBins)];

                var p1 = b1.Points[rnd.Next(0, b1.Points.Count)];
                var p2 = b2.Points[rnd.Next(0, b2.Points.Count)];

                var initialSumBin1 = b1.Points.Sum(p => p);
                var initialSumBin2 = b2.Points.Sum(p => p);
                var initialDiff = Math.Abs(initialSumBin1 - initialSumBin2);

                b1.Add(p2);
                b2.Remove(p2);
                b2.Add(p1);
                b1.Remove(p1);

                var finalSumBin1 = b1.Points.Sum(p => p);
                var finalSumBin2 = b2.Points.Sum(p => p);
                var finalDiff = Math.Abs(finalSumBin1 - finalSumBin2);

                if (finalDiff < initialDiff)
                {
                    Console.WriteLine("Optimized {0}:", i);
                    Test(bins);
                }
                else
                {
                    b1.Add(p1);
                    b2.Remove(p1);
                    b2.Add(p2);
                    b1.Remove(p2);
                }
            }

            Console.WriteLine("Final:");
            Test(bins);

            Console.ReadKey();
        }

        private static void Test(List<Bin> bins)
        {
            // Test.
            for (int i = 0; i < bins.Count; i++)
            {
                Console.Write("Bin {0}, Count: {1}, Sum:{2}, Points:", i + 1, bins[i].Points.Count, bins[i].Points.Sum(p => p));
                //foreach (var point in bins[i].Points.OrderByDescending(p => p))
                //{
                //    Console.Write("{0} ", point);
                //}
                Console.WriteLine();
            }
            Console.WriteLine();
        }
    }

    class Bin
    {
        public readonly List<int> Points;
        public int Id { get; private set; }

        public Bin(int id)
        {
            Points = new List<int>();
            Id = id;
        }

        public void Add(int point)
        {
            Points.Add(point);
        }

        public void Remove(int point)
        {
            Points.Remove(point);
        }
    }
}
</code>```

But I don't have an idea how to set NumberOfSwaps const. In this example I set it by testing... Of course you can't be sure that you got the optimal result.

But for more advanced/academic/production ready algorithms you can start your research here:Bin packing problem

Body:
Just an idea: randomly swap items in bins, something like this:

using System;
using System.Linq;
using System.Collections.Generic;

namespace BinsGenetic
{
    class Program
    {
        private const int NumberOfBins = 10;
        private const int NumberOfPoints = 100000;
        private const int MinimalPoint = 1;
        private const int MaximalPoint = 1000;
        private const int NumberOfSwaps = 10000;

        static void Main()
        {
            // Generate empty bins.
            var bins = new List<Bin>();
            for (int i = 0; i < NumberOfBins; i++)
            {
                bins.Add(new Bin(i + 1));
            }

            // Generate 100 points with weight from 1 to 10.
            var points = new List<int>();
            var rnd = new Random();
            for (int i = 0; i < NumberOfPoints; i++)
            {
                points.Add(rnd.Next(MinimalPoint, MaximalPoint));
            }

            // Insert points into bins by random order.
            int c = 0;
            foreach (var point in points.OrderBy(p => p))
            {
                bins[c].Add(point);
                c++;
                if (c % NumberOfBins == 0) c = 0;
            }

            Console.WriteLine("Initial:");
            Test(bins);

            // Get max and min bin.
            for (int i = 0; i < NumberOfSwaps; i++)
            {
                var b1 = bins[rnd.Next(0, NumberOfBins)];
                var b2 = bins[rnd.Next(0, NumberOfBins)];

                var p1 = b1.Points[rnd.Next(0, b1.Points.Count)];
                var p2 = b2.Points[rnd.Next(0, b2.Points.Count)];

                var initialSumBin1 = b1.Points.Sum(p => p);
                var initialSumBin2 = b2.Points.Sum(p => p);
                var initialDiff = Math.Abs(initialSumBin1 - initialSumBin2);

                b1.Add(p2);
                b2.Remove(p2);
                b2.Add(p1);
                b1.Remove(p1);

                var finalSumBin1 = b1.Points.Sum(p => p);
                var finalSumBin2 = b2.Points.Sum(p => p);
                var finalDiff = Math.Abs(finalSumBin1 - finalSumBin2);

                if (finalDiff < initialDiff)
                {
                    Console.WriteLine("Optimized {0}:", i);
                    Test(bins);
                }
                else
                {
                    b1.Add(p1);
                    b2.Remove(p1);
                    b2.Add(p2);
                    b1.Remove(p2);
                }
            }

            Console.WriteLine("Final:");
            Test(bins);

            Console.ReadKey();
        }

        private static void Test(List<Bin> bins)
        {
            // Test.
            for (int i = 0; i < bins.Count; i++)
            {
                Console.Write("Bin {0}, Count: {1}, Sum:{2}, Points:", i + 1, bins[i].Points.Count, bins[i].Points.Sum(p => p));
                //foreach (var point in bins[i].Points.OrderByDescending(p => p))
                //{
                //    Console.Write("{0} ", point);
                //}
                Console.WriteLine();
            }
            Console.WriteLine();
        }
    }

    class Bin
    {
        public readonly List<int> Points;
        public int Id { get; private set; }

        public Bin(int id)
        {
            Points = new List<int>();
            Id = id;
        }

        public void Add(int point)
        {
            Points.Add(point);
        }

        public void Remove(int point)
        {
            Points.Remove(point);
        }
    }
}

But I don't have an idea how to set NumberOfSwaps const. In this example I set it by testing... Of course you can't be sure that you got the optimal result.

But for more advanced/academic/production ready algorithms you can start your research here:Bin packing problem


问:
Is it legitimate to ask co-workers to use specific browser in an intranet website?
I developed an intranet (local network) ASP.NET web project for my co-workers.

In the development process I used Chrome and Firefox and didn't test much with Internet Explorer.

The website works well with Firefox and Chrome and with IE it had major bugs.

Is it legitimate to ask the users to use Chrome or Firefox?

They are all co-workers (around 15 users).

I don't want to spend time fixing the bugs for IE, some might be related to stuff I can't fix myself (jQuery things), if I wanted to be compatible with all browsers, I would have to make a major re-design,

答: For a small team like yours, yes, it might be legitimate.  That doesn't mean they'll like your decision.  And it may depend on who you're talking about - geeks often prefer Chrome or Firefox, while non-technical types often use Internet Explorer because it's built in and the default.</p>


答: I don't see a problem to set a single supported browser for small intranet applications, if using that browser is within company policy. Ironing out all the little problems with all browsers will likely cost more than an intranet application is worth. </p>

Title: Is it legitimate to ask co-workers to use specific browser in an intranet website?

Body:
I developed an intranet (local network) ASP.NET web project for my co-workers.

In the development process I used Chrome and Firefox and didn't test much with Internet Explorer.

The website works well with Firefox and Chrome and with IE it had major bugs.

Is it legitimate to ask the users to use Chrome or Firefox?

They are all co-workers (around 15 users).

I don't want to spend time fixing the bugs for IE, some might be related to stuff I can't fix myself (jQuery things), if I wanted to be compatible with all browsers, I would have to make a major re-design,


问:
Do I need unit test if I already have integration test?
If I already have integration test for my program, and they all passed, then I have a good feel that it will work. Then what are the reasons to write/add unit tests? Since I already have to write integration tests anyway, I will like to only write unit test for parts that not covered by integration tests.

What I know the benefit of unit test over integration test are

Small and hence fast to run (but adding new unit to test something is already tested by integration test means my total test suit get larger and longer to run)

Locate bug easier because it only test one thing (but I can start write unit test to verify each individual part when my integration test failed)

Find bug that may not be caught in integration test. e.g. masking/offsetting bugs. (but if my integration tests all passes, which means my program will work even some hidden bug exists. So find/fix these bugs are not really high priority unless they start breaking future integration tests or cause performance problem )

And we always want to write less code, but write unit tests need lots more code (mainly setup mock objects). The difference between some of my unit tests and integration tests is that in unit tests, I use mock object, and in integration tests, I use real object. Which have lots of duplication and I don't like duplicated code, even in tests because this add overhead to change code behavior (refactor tool cannot do all work all the time).

答:
You've laid out good arguments for and against unit testing.  So you have to ask yourself, "Do I see value in the positive arguments that outweigh the costs in the negative ones?"  I certainly do:

Small-and-fast is a nice aspect of unit testing, although by no means the most important.

Locating-bug[s]-easier is extremely valuable.  Many studies of professional software development have shown that the cost of a bug rises steeply as it ages and moves down the software-delivery pipeline.

Finding-masked-bugs is valuable.  When you know that a particular component has all of its behaviors verified, you can use it in ways that it was not previously used, with confidence.  If the only verification is via integration testing, you only know that its current uses behave correctly.

Mocking is costly in real-world cases, and maintaining mocks is doubly so.  In fact, when mocking "interesting" objects or interfaces, you might even need tests that verify that your mock objects correctly model your real objects!

In my book, the pros outweigh the cons.


答: Almost every web site requires some additional time and effort to make properly written code and markup to work in IE. That's why clients get charged more. The extra effort is wasted on your people who wouldn't be using IE anyway. So requiring Chrome or Firefox should be easy and sane.</p>


问:
Web versus desktop development - is web development worse?
As a longtime desktop developer looking at doing our first large-scale web application, what are the pros and cons of doing web development?

Is developing a web application much worse than developing a desktop app?  E.g., is it more tedious or annoying?  Is the time to market much worse?  Is the web platform excessively limiting?  If the answer to any of these is yes, then why?

(And how does developing a Flash or Silverlight app compare?)

答:
Web development isn't necessarily worse, it's just very different.

One of the things that separates web development from desktop development is the plethora of radically different technologies you have to master in order to develop a decently complex application.  I mean, you basically need to have a strong knowledge of:

HTML

Javascript

CSS

Some server-side language
(Java/PHP/whatever...)

An RDBMS (or some persistent store
technology)

...and possibly many other things
like Flash, Silverlight, etc.

Whereas, with desktop development you're usually working with a much more monolithic set of technologies.  For example, developing a Java app basically requires you to know Java, and that's it.  (Of course, that's somewhat of a simplification, but the point is web development exposes you to a much wider range of radically different technologies that need to work together to form a functioning application.)


问:
What is the best way to store configurations of shell/script code to execute later?
I am working on a tool (Python, may or may not be important) that will allow a user to maintain a configuration file containing arbitrary shell and/or language code to be executed on particular events and intervals. The code will potentially involve multiple statements.

I understand there are potential behavioral and security risks associated with executing arbitrary code from a file, but I don't think this is a concern because the configuration file is managed only by the end user. However, let me know if I'm overlooking something major.

My main question: what is the best way to store this code in a configurable way?

Some concepts I'm considering to store the code...

In a shared config file (which many Python libraries already look for):

```<code># setup.cfg
[my_program]
command_1 = cd /tmp && touch foobar
</code>```

In a YAML file:

```<code># my_program.yaml
command_1: cd /tmp && touch foobar
</code>```

In a source file as arguments to subprocess.call():

```<code># settings.py
command_1 = [['cd', '/tmp'], ['touch', 'foobar']] # requires special handling of 'cd'
</code>```

In a source file as a function:

```<code># settings.py
import os
import subprocess
def command_1():
    os.chdir('/tmp')
    subprocess.call(['touch', 'foobar'])
</code>```

答:
One option I'm considering is to have users create a Makefile with specific target names.

Advantages:

all commands are locally testable

Disadvantages:

requires make


问:
Is there value denoting a key as "Primary"?
Question: Is there value in denoting a key as "Primary"?

This question is not about the definition of a primary key. It is not about the fact primary's aren't nullable. It is not about implementations such as MySQL which automatically perform clustered index voodoo behind the scenes on primary keys.

NOTE: The question is not about the benefits of auto-number-ID surrogates over natural keys.

Suppose a table has 3 candidate keys. All non-nullable. All immutable. I find no value denoting a key as "secondary" or "tertiary". I don't find the concept of precedence useful when dealing with multiple keys. I find the same logic against "secondary" and "tertiary" flags applies to the "primary" flag.

I even feel the word "candidate" is not useful for a key. It implies the candidate is not as important as the key that won the primary election. I don't feel precedence has any place in describing keys. The attributes of the key itself (unique, non-nullable, etc) should be sufficient.

Would the relational model be missing anything if we did not have the "primary" attribute to describe 1 of a table's keys?

答:
Logically and practically speaking there are really no "primary" keys in the relational model [1] because all candidate keys can and do have exactly the same status, features and function in the relational model: candidate keys are irreducibly unique, non-nullable identifiers for tuples in a relation.

The practice of singling out any one key as "preferred", "most important" or for any other purpose is a matter of convention and convenience rather than necessity. If a relation has only one candidate key then we might just as well call it a "primary" key by default. If a relation has more than one key then the choice of which to call "primary" is only as important as you want it to be and the significance of that choice is defined by the user and/or by the syntax and DBMS features used to define it.

You are certainly not alone in finding the idea of designating a "primary" key of somewhat limited and dubious value. Especially so in the database systems of today, compared to those of decades past. The "primary key assumption" is a controversial notion that is arguably outdated and by rights probably ought to be retired by now. Unfortunately it's an assumption that is heavily entrenched in the mindset and practices of many database practitioners.

[1] E.F.Codd originally used the term "primary key" to mean any and all keys of a relation and stated that a relation could have more than one such key. It was only later that the term "candidate key" appeared in the relational database literature and the term "primary key" took on its modern meaning of denoting one and only one key per relation.