答:
MVC can mean a lot of different things, and the right answer probably looks like, "Whatever works with my framework and whatever else I am using or doing."

This is a topic where understanding history helps you understand why people do things the way they do them, what it means, and how the idea could evolve in the future.  The last is important - if you can figure out how people will do things in 5 years, in 5 years you can have 5 years more experience doing it "the modern way" than anyone else!  For a full version of the history, see http://c2.com/cgi/wiki?ModelViewControllerHistory.

Here is a summary.  Originally MVC appeared for interactive applications.  (I know this seems like a diversion, but this will matter.)  Every single interactive component - every dropdown, etc, had its own model, view and controller.  The job of all three was well defined.  The Controller would have a set of possible events that could happen (someone clicked a mouse, pressed a key, another controller passed a message saying do something) that it was supposed to take care of.  In turn it knew about a view and a model.  The view knew how to draw itself (you were told to scroll down, select item #3, etc).  And the model was in charge of the data that determined what was in the view (eg list of entries for a dropdown).  Very, very granular.  Lots of components.  Lots of dynamic interactions.

MVC is still used this way for interactive applications.

Then the web came along.  One thing programmers do when they move to a new domain is try to carry along existing patterns.  MVC was a proven one.  In the context of the web, the only event of interest is "request page X".  Suppose that is a page where a user can edit their information.  There is going to be a data model associated with it.  Think "User object, with these fields".  There is going to be a view.  Think, "Template for how to show the user."  You can even have different views for the same object - if I look at your home page I am allowed to see different information than you are.

So far, so good.  Where is the problem?  There are many.  Here is a short list.

Generating a dynamic web page is usually much more complex than handling a click of a button in an interactive application.  Therefore each of the three components is doing a more complex thing than they would in the application case.

It is unclear to people what belongs where.  The same code can go in the model, view, and controller, and it is not immediately obvious that it matters where it lives.  But random things tend to be particularly easy to insert into the controller.

Complex web pages include multiple things that want data models - for example a form, a sidebar, ads, and so on.  How do you represent that?

Over a website you generally have many views, but you want to maintain a consistent view across them.  How do you structure your views to allow this, while making them make sense for designers who are not programmers?

Over time we're moving towards richer and more complex interactive pages, with tricks like AJAX.  How do you shoehorn this into a per-page mentality that is natural when handling http requests?

And so on.

There are a lot of possible solutions to these, with different tradeoffs.  In general if you use a framework, and try to solve things the way the framework expects, things work well.  If not, well, then things get challenging.  Hence my advice above to do whatever works with your framework.

But there are general principles.

Since controllers have a complex job to do, and are easy to insert additional logic into, the natural progression of code over time is that everything winds up in the all-knowing controller.  Single large interacting blocks of code tend to not scale well.  So you want to keep everything that can be kept out of the controller, out of the controller.  (Some frameworks make things even simpler by splitting up controllers recursively!)

Business logic almost always belongs in the model.  If you've got a database and an Object Relational Mapper, it is easy to structure models for simple applications as fairly straightforward layers over database tables.  This is a popular design.

The view usually winds up being some sort of template system.  How to handle commonalities is up to your template system.  Understand the system you use, try to work within it.

You're a self-admitted beginner.  I would highly recommend picking a framework, following advised best practices for said framework (even if you later decide they are not best, organizing code like your framework expects tends to be a path of least unexpected surprises), and getting practice with simple applications before tackling anything more complex.  I highly, highly, highly recommend this - before trying to run, make sure that you're good at walking.

But as you walk, come back to this post, look at the list of pain points I gave above, think about your did or didn't hit them, and how you could handle them within what you built.  This type of deliberate "how would I?" self-reflection is a critical part of improving.  As I say, those are known pain points that come up across many different frameworks and I don't think that we've found the best way to handle them yet.

If I had to guess where we'll go, what do I think?

My belief is that as web pages get more interactive, they are becoming more like existing interactive applications.  (Have you used gmail with keyboard shortcuts recently?)  The more that they become interactive applications, the more that it makes sense to use MVC in JavaScript in the way that it is used in interactive applications.  The more complex your front end becomes, the more it makes sense to have the html that delivers that being delivered by code which is structured the same way that the code you are generating is being delivered.

If so, then we should (indeed I believe already are) see front end web pages that have many controllers, many models, and many views which can interact.  These will eventually be pushed back to the server which will be expected to generate those parts of the page with similar granularity (albeit with the ability to pass information around so that the JavaScript library that enables X is actually loaded in the appropriate part of the page for that).

I think this in part because I have worked with a proprietary system that was structured this way.  It was interesting.  There were many controllers, views and models.  However the controllers turned into data structures with some data inheritance to handle commonalities, the views into simple templates, and the models were parametrized by information from the controller.  The concerns were so well separated that we were able to put the three into three different languages (Perl models, YAML controllers, TT templates).  We were able to do things like completely rewrite the back end to the website (literally different pages, accessed in a different order, that were hitting different services) while managing to reuse, unchanged, most of the front end.

It was clear to me that that implementation was not exactly the right way to do it.  But I think those ideas will be rediscovered multiple times, and over the next decade I think that is the direction that a lot of people will head.

If this sounds likely to you, and you like front end work, then after getting some simple sites working in whatever server language you want (from the sounds of it PHP, though I personally would prefer anything else), I'd suggest learning JavaScript, picking up a popular MVC framework like http://angularjs.org/, and trying to write interactive applications using it.  Pay close attention to what works and doesn't, make your own theories, experiment, get feedback, and you'll be likely to be ahead of the future when the future arrives.

(How did this answer get so long?  Oh well, it is written, might as well post it.)

Title: application logic, business logic, models, controllers - where to put the application's brains?

Body:
I'm trying to wrap my head around models, views, and controllers, but I feel as though the more I read, the more conflicting information I seem to encounter. I guess the general goal is--as far as I've seen--to shoot for fat models and thin controllers, but I'm still a bit baffled by where to put what. Can I give an example from something I'm working on?

This is just a personal project that I'm messing about with in PHP for fun--a mini-game of sorts. Adding timed tasks to an itinerary and collecting rewards when the task completes. So a class kind of like this exists:

```<code>class ItineraryEntry {
    public $user_id;
    public $task_id;
    public $completion_time;
}
</code>```

And another class like this:

```<code>class Task {
    public $task_id;
    public $description;
    public $duration; //in seconds
}
</code>```

So in the user interface, the user sees a task description and clicks something like "Add to Itinerary". Now if I'm understanding correctly, the controller needs to pick up that request and do something with it. But...how much? So for example, I need to figure out when the task will complete. Keeping it simple, that's merely time() + the duration of the task. So does the controller do that calculation and then give it to the model to validate, or does the model just handle all of it? And the controller is really just a glorified router of data?

Then the second part is what happens when an itinerary task completes. So from the user interface, a task will show as completed if the completion time is in the past, and the user will have to click something like, "Claim Rewards". Let's just say it's...I don't know...XP (i.e., experience points)--something that gets updated on the user's account. And let's say that the amount of XP is calculated in some way based upon the difficulty of the task, time required, etc.

So where would I put that calculation? Is that inside the model class for my user object, or do I have a controller that figures all of that out and then sends it to the user object? In the model for my itinerary entry model? And the reason I ask this specifically is because any kind of Claim Rewards code would have to do a couple of things at least:

Actually claim the reward and update the user's account

Clean up the expired task from the database (or marking it completed or something)

So it would be interacting both with the user and the itinerary entry.

A little specific guidance would be really helpful. My brain is starting to hurt from reading all of these explanations that are kind of like what I need to know, but not totally. So thanks in advance!


问:
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.

答:
As well as checking your contract, it is obviously important that you don't take code from the consulting firm that you work at to use on your freelance projects.

In my experience bosses have liked that the fact that I've been willing to do freelance work - it is practice for your day job after all.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Is fewer lines of code always better?
Which of these programming styles is better?

```<code>var result = methodOne(methodTwo(a, methodThree(b)), c, d);
</code>```

or

```<code>var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);
</code>```

答:
In a nutshell, the human brain,for most common people, can hold 7 different things at best. This is for common people, and this is an average. (I'm afraid I haven't found the source of my statement)

As a consequence, if you want to write code that anyone can read, it should not use more than 7 differents variables/concepts/functions/operations.

for example:

```<code>rotate(translate(rotate(translate(circle,50,0),0,10,pi),-50,0),0,10,pi)
</code>```

there it is really hard to understand what is going on, astonishingly this lines does absolutely nothing in the geometric sense:

```<code>circle = translate(circle,50,0)
circle = rotate(circle,0,10,pi)
circle = translate(circle,-50,0)
circle = rotate(circle,0,10,-pi)
</code>```

this is also why it is easier to read functions that are less than 40 lines of code too.

Title: Is fewer lines of code always better?

Body:
In a nutshell, the human brain,for most common people, can hold 7 different things at best. This is for common people, and this is an average. (I'm afraid I haven't found the source of my statement)

As a consequence, if you want to write code that anyone can read, it should not use more than 7 differents variables/concepts/functions/operations.

for example:

rotate(translate(rotate(translate(circle,50,0),0,10,pi),-50,0),0,10,pi)

there it is really hard to understand what is going on, astonishingly this lines does absolutely nothing in the geometric sense:

circle = translate(circle,50,0)
circle = rotate(circle,0,10,pi)
circle = translate(circle,-50,0)
circle = rotate(circle,0,10,-pi)

this is also why it is easier to read functions that are less than 40 lines of code too.


问:
Refactor working code for reuse or duplicate?
I have always avoided duplicating code regardless of the circumstance.  For example, if I have a working piece of functionality that needs to be re-used by different entities, I always refactor to make this functionality available.  Under no circumstance would I duplicate code.  I am probably a little rigid when it comes to this but I really do not like duplicating code.

I currently had a slight disagreement with our Team Lead who suggested that instead of refactoring, I should copy entire piece of functionality I require into a different class and then we can decide how best to refactor at a later date. This is even after confirming  that my previous refactoring efforts did not break any of the unit tests.

I further had this conversation today with my previous manager, and his mentor, who both sided with my Team Lead.  Their argument is incurring technical debt is OK, and almost always preferable, especially if you are running into time constraints, which I understand.  My counter argument was yes, we do not want to skip deadlines but one must always consider the cost of refactoring and this usually should be the first instinct, especially if we are simply moving functionality into a new location that renders it accessible to all.  Proper unit test can also ensure that refactoring efforts do not break existing functionality.  Also is it not always better to pay off the debt now rather than later?  I can only imagine what this task will entail if all members of the team simply duplicated code.

Suffices to say that we had to agree to disagree.  In his book titled Clean Code, Robert Martins emphasis continuous refactor during development so I was surprised by the response of my previous manager.

What are you opinions on this?

答:
Yes, incurring technical debt is bad. Yes, you should always refactor as you develop.

In an ideal world.

Unfortunately, we do not live in an ideal world. Sometimes, we have to do things we're not happy about. I'm pretty sure your Team Lead is aware that not taking the time now will mean more work in the future - but he's had to make a decision. There are many reasons why this would be so.

Ideally (that word again), in this situation, there should be an allowance for some time to refactor after the deadline before moving on to new work. If that doesn't happen, then there is definitely some code management smell there - but your disagreement with the practice will likely not have an effect, and any attempt to force the issue will just make your position more uncomfortable.

As we only have your side of the discussion to go by, it's hard to answer in a balanced way - for example, you don't really say how big this bit of functionality is. Also, you don't say how often this situation occurs.

Ultimately, if you don't like the practices at your current organisation, there are plenty of others out there that you would fit in better at.


答: Not sure what is in your case, but the fate of fact is, "tell your boss and he wont permit you". Most employers usually have it written somewhere on the contract that would say, "you will not engage into any activity that will have an impact on your commitment for your current job". Having to work for someone, particularly on large scale may take away some time from your current work. If there is nothing on the contract that says you can't, I would suggest that you put less effort on the external work. Say 2 hours each working day and a bit more during the weekends. That's how I do my outside office work :)  </p>

Title: Should I ask/tell my boss before freelancing?

Body:
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.


问:
Python/Database Website development
I want to create my own website that would allow me to acess a database in the server and do inserts and lookups in a user friendly way. I am a seasoned user of linux and C/C++, and also have experience with Python and sqlite3, but i don't have any experience in Web development, so i have no idea where to start.

I have researched online and the best i came up with was an Apache/Nginx server together with an fcig or wscgi and Django, so that i would have database and python integration through a Django App.

Can someone tell me if this is the way to go or if there is some easier (or better) way to accomplish what i want?

答: Since you know Python already I see no reason not to go for Django. It should be fairly easy to set up and try out a quick project to see if you like it. Like with everything there's a learning curve, but from what I've seen the tutorials and documentation to get you up and running is rather good.</p>

Title: Python/Database Website development


答:
You should always talk to your boss when considering doing freelance work outside of your normal job, unless it's something completely unrelated.
If you have a proper contract, it'll probably contain some paragraphs about that.

Aside from the legal things, it's always a good idea to be open and honest towards your employer. By being honest there will be no surprises. What if the company you work for was trying to close a deal with your potential client, and you win the deal? That could get real awkward.


问:
When to start thinking about scalability?
I'm having a funny but also terrible problem. I'm about to launch a new (iPhone) app. It's a turn-based multiplayer game running on my own custom backend. But I'm afraid to launch.

For some reason, I think it might become something big and that its popularity will kill my poor lonely single server + MySQL database.

On one hand I'm thinking that if it's growing, I'd better be prepared and have a scalable infrastructure already in place.

On the other hand I just feel like getting it out into the world and see what happens.

I often read stuff like "premature optimization is the root of all evil" or people saying that you should just build your killer game now, with the tools at hand, and worry about other stuff like scalability later.

I'd love to hear some opinions on this from experts or people with experience with this. Thanks!

答:
There's no reason to optimize until you know optimization is needed. How do you know optimization is needed? You measure.

Assuming that your server has some sort of web-based interface, you can simulate a lot of users by using tools such as Apache JMeter. Learn how to use the tool, then start stress-testing your back-end. You should be able to learn enough to know what the limits are to your system. You can then combine that information with the number of users you have and the average number that are running at one time, to decide when to scale up.


问:
Must-have tools and practices for an agile start-up
I've been working in the software industry for a few years now.  I've seen Waterfall in practice, and I've seen several projects attempt Agile with varying degrees of success... which got me thinking.

What are the bare-minimum requirements for an Agile startup to be successful?  I'm thinking in terms of tools, practices, team roles (e.g., source control, automated testing, BA role).

I'd like to be able to draft a list of tools/practices/etc that are absolutely essential for the long term sustained success of a startup wanting to do Agile.

I ask because I'd like to start my own software company eventually.  Most of my experience is in SCRUM so I'm naturally biased towards it and I've already developed an opinion of what the minimum requirements for a SCRUM team to function are.  But, being only human, and being only one sample, I wouldn't be surprised if my opinion was flawed or incomplete.

I'd appreciate any and all insight and experience.

Thanks

答:
Tools

You definitely will need source control. Preferably one that includes a web interface so that every day you can start off by seeing what people have checked in recently.

You will need a team space where your developers, QA, and product owners can work together to deliver a product.

You will need a continuous integration server so that you're constantly running tests against your software.

You will need an automation framework of some sort, that lets you easily write automated acceptance tests. It doesn't have to be fancy, and could be built on top of the various *unit frameworks, but you need something.

You need a team wiki. Many source control systems come with one. You need a quick and easy way to create internal documentation.

You need an issue tracker. Many source control systems come with one of these, too. You need a way to track defects. You can use sticky notes on a whiteboard if you're good about keeping your bug count to a minimum.  Consider choosing an integrated wiki, issue tracker and source code control system in one.

Equipment

You will need whiteboards and sticky notes. There are many opinions on this, but in my experience nothing works better than physical boards and story cards. You can use an electronic story board, of course, and ultimately it boils down to what works best for your team.

Procedures

You should start by following all of the scrum rituals. That's not to say they are the best, but before you can run you need to walk. Start with two week sprints, do your standups every day, your retrospectives and demos every two weeks. Be religious about it, until the point comes where you can decide what works for your team and what doesn't.

You must build your software from day one to be buildable in a single step and be able to be automatically deployed. You don't want your development team to have to spend time manually building or installing software all the time. These features are almost impossible to add after the fact, it needs to be part of the culture from day one.

Roles

You need a product owner. This is the person that straddles the line between the customer and the development team. They should be technical enough to have meaningful conversations with the development team, but they also need to know the product space and be able to speak intelligently with customers.

You will need developers. Ideally these will be dedicated 100% to creating the product. A developer shouldn't also be a product owner, scrum master, or manager.

You will need QA developers. These people are the advocate of the customer. They are responsible for guiding the team toward developing high quality software. They aren't just testers, they work with the team to understand what is being developed, and help the team build testable software. Ideally these people are software developers who have a passion for testing, since a large part of the role should involve writing automated tests and maintaining the testing framework.

Optionally, it would be good to have a dedicated scrum master. Their job is to focus on the productivity of the team, rather than on the product being built. Having someone in that role will help the team come together and work at their peak.

Culture

Above all, you need to build a culture that understands that software development is all about the customer. Nobody will buy your software because they want to use your software, unless you're creating a game. Instead, they use your software in order to accomplish some other task. Your job is to deliver software that makes completing those tasks easier.

You need to foster a culture of communication, and one where software quality has top priority. That means each story is fully tested before moving on to the next. The idea that you'll test something in a final sprint needs to simply be unacceptable to everyone on the team.

Finally, you need a culture that values a 40 hour work week. While a can-do attitude is important, and people must be willing to roll up their sleeves and work extra hours on occasion, those extra hours must be the exception rather than the rule. Software development is largely a creative task, and you can't be creative when you are overworked. Happy team members are productive team members.


问:
Should I fork in case the upstream deletes
I'm creating an open source PHP project that reuses other open source code instead of reinventing the wheel. I'm using composer to pull these projects into my vendor folder. What happens if these vendors delete their repository & all traces of their code from the internet? Now composer can't download the project. Should I fork every project I'm depending on, and depend on the fork? Seems like a pain, but the only 'safe' way to ensure the vendor can't delete things my project needs to run.</p>

答:
I wouldn't start out with the assumption that the maintainer of a third-party library that you use will pull the rug from underneath you. It is far more common that a maintainer leaves a project abandoned on the net than that they actively remove it.

In the off-chance that a dependency of your project does get pulled off the net, chances are that you still have a local copy of the source code of that project somewhere in your build, test or deployment environment and you can use that to fork the project then and there.


答:
I think there is no clear answer but here are some thoughts:

Process: Right at the beginning, most likely the team size is so small (<=3 developers) that you don't need a well-tuned process like SCRUM. It will become more important if you become successful and grow, but I wouldn't consider it crucial at the start.

Tools: Depends on want you want to do and what your experiences are. Startups have no legacy code, so they will can generally go for newer technologies. (Who knows what that will be in the next year. Once it was Rails, now it seems to be NodeJS.)

When it comes to programming languages, the only safe recommendation is to value productivity over performance (e.g., Ruby, Python, Javascript/coffescript instead of Java or C++).

Practices: You should strive for as much automation as possible. You will need it later anyway and it will help you right from the start. Automated testing is a must, and the setup and deployment of your applicaton should be easy. Put your configuration files under version control, not only your source code. Configuration management tools can also help (e.g., Puppet, Chef).

Title: Must-have tools and practices for an agile start-up

Body:
I've been working in the software industry for a few years now.  I've seen Waterfall in practice, and I've seen several projects attempt Agile with varying degrees of success... which got me thinking.

What are the bare-minimum requirements for an Agile startup to be successful?  I'm thinking in terms of tools, practices, team roles (e.g., source control, automated testing, BA role).

I'd like to be able to draft a list of tools/practices/etc that are absolutely essential for the long term sustained success of a startup wanting to do Agile.

I ask because I'd like to start my own software company eventually.  Most of my experience is in SCRUM so I'm naturally biased towards it and I've already developed an opinion of what the minimum requirements for a SCRUM team to function are.  But, being only human, and being only one sample, I wouldn't be surprised if my opinion was flawed or incomplete.

I'd appreciate any and all insight and experience.

Thanks


答:
Your server will be used interactively by users. This means that latency is affecting user-experience in a very profound way. Bad latency always results in bad user-experience.

At least do some ad-hoc load-testing as described by Bryan.

A more serious approach

Do some simulation runs and find out what latency does to your user-experience (either using a network delay simulation or just sleep() inside of your application). Find out at what latency it's getting noticable, getting annoying and getting unusable.

Then comes the first step in the direction of optimizing. Decide on a SLA for your server : e.g. at worst 10% calls with annoying latency and 1% calls with unusable latency. With those limits you can use load-testing to find out how many users your server can support.

Pure throughput testing without measuring latency (or at least manually using the server during the load test) is not that useful because it doesn't tell you whether the measured throughput numbers result in bearable user-experience.

A very nice presentation about measuring latency by Gil Tene: http://www.infoq.com/presentations/latency-pitfalls

Title: When to start thinking about scalability?

Body:
I'm having a funny but also terrible problem. I'm about to launch a new (iPhone) app. It's a turn-based multiplayer game running on my own custom backend. But I'm afraid to launch.

For some reason, I think it might become something big and that its popularity will kill my poor lonely single server + MySQL database.

On one hand I'm thinking that if it's growing, I'd better be prepared and have a scalable infrastructure already in place.

On the other hand I just feel like getting it out into the world and see what happens.

I often read stuff like "premature optimization is the root of all evil" or people saying that you should just build your killer game now, with the tools at hand, and worry about other stuff like scalability later.

I'd love to hear some opinions on this from experts or people with experience with this. Thanks!


答:
Contracts I've seen usually have some clause about this. For example, I'm forbidden to work on side projects in my employer's core industry. Everything else is fair game so long as it doesn't impact my daily performance.

If you don't have a contract, you can either assume a similar arrangement or ask your boss explicitly. I am not a lawyer, but I think if you are reasonable (i.e. don't reuse code written at work, don't use software or hardware provided by your employer, don't become a direct competitor with your employer, etc.), then you should be okay. It's then a matter of deciding whether it's better to ask forgiveness or permission if your employer does have an issue with your side work.


问:
Where to put interface in .Net
I have VB.Net project, with a class with a couple of abstract (mustoverride) properties, that I am thinking about moving into an interface.

My question, is structurally how do I do this?  Currently all of the classes that would be implementing this are derived from this base class, so it might make sense to put it in the same file.  Or I could create a separate interface file and put it in the same directory as the base class. Another option, would be to create a separate directory for interfaces (of which the project currently has zero) and put the file the.

After writing this up, I'm strongly inclined towards the second option.  I've looked around, but haven't found any guidance on this.  What would be the best option and why?

答:
I would group all my classes and interfaces in a separate folder. Everything should be grouped by functionality and not by whether it is a base class, an interface or whatever.

What would happen if you had a complex design pattern, would you subdivide the interfaces in separate folders?

Title: Where to put interface in .Net


答:
Common guidance in .NET land, in most cases, is to have every class and interface in their own  file. With a 1:1 correspondance between files and classes, navigation becomes  easier. This argues against option #1.

Regarding the choice between #2 and #3, I would argue for the former, with some caveats. I don't think you should have a folder for interfaces, but rather a folder structure based on the domain model. Group your files by subject, not into classes vs. interfaces.

The main caveat, though, if that once your application gets bigger, it might get split off into different projects, and not all projects can reference the project where the interface might be defined. In this case, we'll often create a separate project for contracts and interfaces, which is then referenced by other projects.

Title: Where to put interface in .Net

Body:
I have VB.Net project, with a class with a couple of abstract (mustoverride) properties, that I am thinking about moving into an interface.

My question, is structurally how do I do this?  Currently all of the classes that would be implementing this are derived from this base class, so it might make sense to put it in the same file.  Or I could create a separate interface file and put it in the same directory as the base class. Another option, would be to create a separate directory for interfaces (of which the project currently has zero) and put the file the.

After writing this up, I'm strongly inclined towards the second option.  I've looked around, but haven't found any guidance on this.  What would be the best option and why?


答:
From your description it sounds like there are two possible outcomes:

The game is a failure and then you don't care.

The game is successful and then your backend won't be able to deal with the load and the outcome would be a failure.

Hmmm.

Here are some questions to ask yourself:

How many users can your current backend handle with acceptable performance?

Do you have some sort of plan to limit the impact to current users if you're seeing some sort of rapid growth (e.g. temporarily pull the game from the app store)

How quickly can you come up with a better backend if you are successful?

What are the business implications of waiting.  Can you feed yourself?  What are the risks?

What are the business implications of releasing now given the answers to the question above.

The answer to your question should become evident once you consider these.  No expert can tell you what to do without more information as every system is different and every business is different.


问:
Why is the game industry, specifically , so harsh on programmers?
On hackernews and /r/programming I've heard several reports of how the games industry is incredibly harsh on programmers.  Someone on this site also linked this blog post in an answer I read recently.  According to various reports, programmers in the games industry are severely overworked.  Perhaps not when working for small games companies, but definitely when working for places like EA(the place discussed in the blog post).

So my question is, why?  I'm a developer for a large networking company, I sometimes work more than 8 hours a day, but I wouldn't dream of working 12 hour days 6 days a week like the blog post describes.  I'd quit and move on without a second thought.  Why does the games industry, specifically, have this problem?

答:
This is just a theory, but I think it is due to the compulsive nature of games and gamers. They love to play games for hours on end and they're creating a product that has a goal of the user being engaged as long as possible. My guess is people in the movie and music industry run into similar hours.

Try to imagine someone who creates business software having a strong desire to add as many features as possible because they would be disappointed as a user not to have them. As a networking software developer, do you come across hundreds of ideas in the form of, "You know what would be cool?" How many places do you get that kind of passion?

Product Release Fanfare - there is such a cult-following and they are in the entertainment industry, so I think they get caught up in the release drama. When you make the hype so big, you just have to get it done if it kills you. There are other kinds of software that have this, but not like gaming. Having enough time to burn disks has to put some pressure as well. Not a lot of other software is distributed by disks anymore.

Check out this movie. Indie Game, I don't think this only applies to big companies. It's the nature of the beast.


答: Everyone wants to make video games. It sounds awesome. This creates competition among prospects. The employers set the conditions of competition, which in this case has turned into a "who can take the most crap" competition.</p>

Title: Why is the game industry, specifically , so harsh on programmers?

Body:
On hackernews and /r/programming I've heard several reports of how the games industry is incredibly harsh on programmers.  Someone on this site also linked this blog post in an answer I read recently.  According to various reports, programmers in the games industry are severely overworked.  Perhaps not when working for small games companies, but definitely when working for places like EA(the place discussed in the blog post).

So my question is, why?  I'm a developer for a large networking company, I sometimes work more than 8 hours a day, but I wouldn't dream of working 12 hour days 6 days a week like the blog post describes.  I'd quit and move on without a second thought.  Why does the games industry, specifically, have this problem?


答: I think if you don't break/violate any rule of your main job and not harming your main job by freelance job, then its fine to do freelance job, and you should be independent of asking anyone about what you do at your extra time.</p>


答:
It's actually quite an easy choice.

Right now, you have zero users, and scalability is not a problem.

Ideally, you want to reach the point where you have millions of users, and scalability becomes a problem.

Right now, you don't have a scalability problem; you have a number-of-users problem. If you work on the scalability problem, you will not fix the number-of-users problem, which means you will have solved a problem you don't have yet, and you will not have solved the problem you do have. The most likely result is that your product won't make it, and all your work will be for nothing.

If you work on the number-of-users problem, you will solve a problem you have right now, and then you can focus on the next problem, which might be scalability.

The nice thing about scalability problems is that, by definition, having them usually means business is pretty damn good, and this in turn means you can afford to spend money on optimizing for scalability. You don't go from zero users to ten million overnight, and if you keep an eye on the system's performance, you will have plenty of time to optimize when the time comes.

Of course it helps to keep scalability in mind while writing the code you need right now, but it doesn't make a lot of sense to spend dozens or even hundreds of man-hours on a feature of which you don't know if you'll ever need it, and the most likely scenario is that you won't. Right now, your main concern is to ship. What happens after that; well, you can worry about that later.


答:
TL;DR You should think about scalability before the first line of code is written.

First things first.  Scalabilty != Optimization

You should think about scalability before the first line of code is written.  This doesn't mean that you build out some massive infrastructure on the off chance your game might be a hit.  Thinking about scalability means:

Making sure the code is written so it scales.  I've seen plenty of projects where no thought was given to needing to scale.  The results are a codebase that won't scale regardless of the hardware you throw at it, or is prohibitively expensive to scale.

Figure out your scaling strategy.  Have a plan on how to support all the users.  You have a MySQL db, are you going to shard it or cluster, or something else.  Strategies like sharding require some forethought because it places requirements on the architecture.  Clustering, less so.  Are you supporting sessions, and how will sessions react with multiple front end servers.  Will you need sticky sessions, in your load balancer.

Figure out implementation strategy.  Are you going to use AWS for scaling.  Can you leverage any products or services that give you dynamic scaling out of the box?  This also involves understanding your costs.

BUT it sounds like you already have a codebase.  The question now is when to start scaling.  This is completely dependent on your code.

If your code lends itself to scaling then you have the hard part done.  You can get an AWS account, spin up servers as needed and away you go.

If your code doesn't scale or has bottlenecks then you have work to do.  You need to identify what your bottlenecks are and fix them.  The "when" is really hard to know.  Some services plateau, some rise steadily, and some explode.   Deciding when to throw resources at something like scaling is usually a function of business and it's evaluation of the risks.

In your position, I might release as a "beta" and manage user expectations.  That way I can get the product out, and see how it unfolds.


问:
Can we reduce confusion in line-based diff tools by annotating the code with some unique tokens?
Let's say I have

```<code>procedure1() {
    --body of first procedure--
}
</code>```

Then I rename it into procedure2 and create a procedure1 above it:

```<code>procedure1() {
    --body of second procedure--
}

procedure2() {
    --body of first procedure--
}
</code>```

Not once a line-based diff tool has highlighted the code from --body of second procedure
all the way to procedure2() { as new code inside procedure1.

This is bound to happen, since most diff tools are oblivious of the underlying structure of the source code. AST-based diff tools can't work very well either, because of several reasons and I know what people really want is a semantic diff tool, but that's not going to happen.

I haven't seen a discussion though, about whether or not it would be practical to annotate the code in such a way that a line-based diff tool would understand the underlying structure of the source code.

For example, I could throw in some UUIDs in the code, like this:

```<code>//BeginBlock{E999A3BF-626E-428F-A2C1-6AFF0CD22BF2}
procedure1() {
    --body of first procedure--
}
//EndBlock
</code>```

And the modified code would look like this:

```<code>//BeginBlock{7C734F0A-92F4-45EB-B653-DBB9A0F18354}
procedure1() {
    --body of second procedure--
}
//EndBlock

//BeginBlock{E999A3BF-626E-428F-A2C1-6AFF0CD22BF2}
procedure2() {
    --body of first procedure--
}
//EndBlock
</code>```

The point is to assign some tokens (unique within a file or project) to some marks that would reflect part of the structure of the source code.

An IDE could update those annotations automatically and they could help a diff tool better detect structural changes. The tool would scan the code once to identify the sections of the program (and how they've been moved around) and then compare those blocks having the same ID.

Do you think this approach is practical?

答:
Well, in the first place I could argue that creating a new procedure1 that does what procedure2 did, with the same signature, is begging for trouble.

Even were procedure1 to be the most natural name for the new procedure, you ought to differentiate it at the name level, to prevent confusion down the line.

On a change of this import, the procedure1 name ought to no longer exist, thereby "informing" all dependant sources that something has changed that they need to react to.

Then, you already have something that can take up the role of an UUID -- function documentation comments.

I have tried modifying a simple file with rudimentary pseudo-Javadoc comments in the way you indicated.

The diff tool in line mode correctly indicates that a new procedure has been added, and the old one has had its name changed.

Granted, the final closing brace has been misrepresented, and this could be avoided by adding a serial number or date stamp to the closing brace (i.e. } // 20130705), but this seems more trouble than it's worth.

```<code>/**                                                             /**
 * Procedure 1, doing things.                                    * Procedure 1, doing things.
 *                                                               *
 */                                                              */

procedure2() {                                                | procedure1() {
        // Do operation 1                                               // Do operation 1
        // Do operation 2                                               // Do operation 2
}                                                             <
                                                              <
/**                                                           <
 * Procedure 2, the new one.                                  <
 *                                                            <
 */                                                           <
                                                              <
procedure1() {                                                <
        // Do operation 3                                     <
        // Do operation 4                                     <
}                                                               }

procedureFinal() {                                              procedureFinal() {
        // Finalize.                                                    // Finalize.
}                                                               }
</code>```

Body:
Well, in the first place I could argue that creating a new procedure1 that does what procedure2 did, with the same signature, is begging for trouble.

Even were procedure1 to be the most natural name for the new procedure, you ought to differentiate it at the name level, to prevent confusion down the line.

On a change of this import, the procedure1 name ought to no longer exist, thereby "informing" all dependant sources that something has changed that they need to react to.

Then, you already have something that can take up the role of an UUID -- function documentation comments.

I have tried modifying a simple file with rudimentary pseudo-Javadoc comments in the way you indicated.

The diff tool in line mode correctly indicates that a new procedure has been added, and the old one has had its name changed.

Granted, the final closing brace has been misrepresented, and this could be avoided by adding a serial number or date stamp to the closing brace (i.e. } // 20130705), but this seems more trouble than it's worth.

/**                                                             /**
 * Procedure 1, doing things.                                    * Procedure 1, doing things.
 *                                                               *
 */                                                              */

procedure2() {                                                | procedure1() {
        // Do operation 1                                               // Do operation 1
        // Do operation 2                                               // Do operation 2
}                                                             <
                                                              <
/**                                                           <
 * Procedure 2, the new one.                                  <
 *                                                            <
 */                                                           <
                                                              <
procedure1() {                                                <
        // Do operation 3                                     <
        // Do operation 4                                     <
}                                                               }

procedureFinal() {                                              procedureFinal() {
        // Finalize.                                                    // Finalize.
}                                                               }


答:
While I won't argue with any of the suggestion @BryanOakley has already put forth, I would like to point out that in the end, the tools don't really matter.  What matters is the people you have working on the project.

Each member of the team needs, first and foremost, to be a good communicator.  They need to be able to talk to the customers--and each other--and in order to understand what is to be done and allow others to understand what is being done.  If the communication is there, you are 80% of the way to being agile.

The other 20% is that each team member needs to be able to pick up whatever ball lands in front of them and run with it.  If someone has "downtime" they should automatically be looking to see how they can help the other members.

Alistair Cockburn calls agile software development "the Cooperative Game" for a reason--it is about people cooperating to achieve something great.  "Individuals and interactions over processes and tools" is the first value of Agile development.


答:
I would say that both examples are equally bad, but that is just because of the insufficient example code. To be able to say if one of the two is better, you need to provide a real example.

There is absolutely no correlation between the number of source code lines, and the quality of the code.

Assuming that we disregard the obvious fact that the code needs to do what it is supposed to do, the most important aspect is that it is easily understood by the readers.

The "classic" way to accomplish this is to add code comments that describe the functionality of the code. In my personal experience, it is even better to use descriptive identifiers for methods, variables and constants.

If you for example see a source code sequence like this, you will immediately understand what it is supposed to do, and you can examine the individual methods and variables to (hopefully) just as easily determine that they do what they are supposed to do:

```<code>if (a_new_game_is_starting && hand_not_dealt_yet()) {
  deal_new_hand_to(all_players_at_table);
}
</code>```

In the example above, there is no need to add any comments at all. What would a comment say that is not easily understood from the actual code? This is something to strive for - to not need to add comments to the code to describe what it does.

This is not something that is hard to do. All it requires is that you think about what you really are trying to accomplish, and name your identifiers from a functional point of view.

Title: Is fewer lines of code always better?

Body:
Which of these programming styles is better?

```<code>var result = methodOne(methodTwo(a, methodThree(b)), c, d);
</code>```

or

```<code>var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);
</code>```

Body:
I would say that both examples are equally bad, but that is just because of the insufficient example code. To be able to say if one of the two is better, you need to provide a real example.

There is absolutely no correlation between the number of source code lines, and the quality of the code.

Assuming that we disregard the obvious fact that the code needs to do what it is supposed to do, the most important aspect is that it is easily understood by the readers.

The "classic" way to accomplish this is to add code comments that describe the functionality of the code. In my personal experience, it is even better to use descriptive identifiers for methods, variables and constants.

If you for example see a source code sequence like this, you will immediately understand what it is supposed to do, and you can examine the individual methods and variables to (hopefully) just as easily determine that they do what they are supposed to do:

if (a_new_game_is_starting && hand_not_dealt_yet()) {
  deal_new_hand_to(all_players_at_table);
}

In the example above, there is no need to add any comments at all. What would a comment say that is not easily understood from the actual code? This is something to strive for - to not need to add comments to the code to describe what it does.

This is not something that is hard to do. All it requires is that you think about what you really are trying to accomplish, and name your identifiers from a functional point of view.


问:
Is there a version control system that can show changes to a specific method or function?
Sometimes it would be nice to be able to say something like:

```<code>(git|svn|hg|etc) diff Foo.c:main
(git|svn|hg|etc) log log Foo.c:main
</code>```

to see the changes made to a specific function within a source file since the last commit, or the complete history of changes. My question is two-fold:

Does something exist that does this?

Would such a tool be practical? It would have to do some simple parsing of the code at each revision in order to compare different versions of the function; would the overhead be too much for it to be efficient?

答: ENVY and StORE both do that. It's interesting that, as with Monicello that Logan Capaldo mentioned above, these too are for Smalltalk.</p>


答:
More important than readability is maintainability, because the main reason we read code is to maintain it.
Maintaining often means making changes to the code because of small or large changes in requirements.

SO, think about what changes in requirements there might be, and try to make them as easy to do as possible. If you can lead the maintainer right to the relevant code, and let them make the changes with minimum editing, they will think you are a great programmer!

OTOH, if people are reading the code to verify its correctness, make sure your reasoning is clear as to why it is correct.
If people doubt the correctness of your code, they are likely to re-write it, which is likely to break it.
To prevent that, make sure the code explains itself.

Also, be sure to explain your performance-related decisions, because one way good code gets destroyed is by being re-written in a misguided attempt to make it faster.

Title: Is fewer lines of code always better?


问:
Representing floating-point numbers in bytecode
How do interpreted languages typically go about representing floating-point numbers in their bytecode?  For example, suppose I've got a Java program with the line

double a = 3.0;

What does 3.0 look like in the program's bytecode?  I see two possibilities:

1) Writing the bit-level representation of the in-memory number into the bytecode, and then just reading it back into memory when we need it.  There are probably problems with portability here (the size of double on different machines can vary, so how do we store a number in bytecode in a portable way?).

2) Write a canonical representation of the number into the bytecode which can be decoded when program execution time comes.  The literal string 3.0 might serve that purpose here, but then we're wasting execution time parsing a floating-point number during runtime.

So my question is, which strategy is most common/efficient/best?  You can feel free to cite examples from different interpreted languages that compile down to bytecode (Python, Lua, etc.), or merely point me in the direction of some resources of some relevant articles if that's necessary (I've been Googling quite a bit, but few virtual machines are well-documented).

答:
Most languages do something like #1, that is, they specify a particular binary encoding, but said encoding is almost invariably IEEE-754 because that is the floating-point standard that a majority of architectures implement. A “double-precision” IEEE-754 floating-point number is defined to be 64 bits.

Examples:

The Java class file format specifies the encoding of floating-point values stored in the constant table and as immediate operands to instructions:

The high_bytes and low_bytes items of the CONSTANT_Double_info structure together represent the double value in IEEE 754 floating-point double format (§2.3.2). The bytes of each item are stored in big-endian (high byte first) order.

The Lua VM also assumes IEEE-754 floats:

Number is the Lua number data type, normally an IEEE 754 64-bit double.


答:
Games are written on a prospective basis - it is hoped that people will pay to play.

Games don't make money until they hit the shelves - a delay in shipping can kill (and has killed) development companies or publishing companies.

Games are surprisingly low-margin - the retail price is split between the retailer, the software company, the publishing company, and in the case of consoles, licence fees. There's advertising, shipping, salaries, and rent to pay for - plus stockholders want some profit.

Most other software (not all, but most) is written on a contractual basis - there is a business user who wants it, or a number of business users who will pay some money up front for it (like how MS and Apple got starter money in the 70s and 80s). This means that the client can be charged for milestone deliveries - unlike games.

That said, the abundance of programmers who want to get into the industry means that games software companies can suffer surprisingly high rates of churn in their staff.

Games developers themselves can take some of the blame - I know a few, and at the start of a one or two year game project, they're playing around, trying cool stuff, and then end up in 3 months of crunch development. That's more of a cultural thing - it's rare to see this in business software companies that run on fixed shipping dates - they tend to have rigid schedules for research and development. Other companies that have a "ship it when it's done" culture, like Google or Valve, are different again. If they're good, and get the balance right, all the cool stuff makes it into the final game. It doesn't always work out, though.


问:
Is "Mapper" a valid design pattern or is it a variation of the "Factory" pattern?
A common pattern I see is what's known as the Mapper pattern (not to be confused with DataMapper which is something else entirely), which takes as an argument some kind of "raw" data source (e.g. an ADO.NET DataReader or DataSet) and maps the fields to properties on a business/domain object.  Example:

```<code>class PersonMapper
{
    public Person Map(DataSet ds)
    {
        Person p = new Person();
        p.FirstName = ds.Tables[0].Rows[0]["FirstName"].ToString();
        // other properties...
        return p;
    }
}
</code>```

The idea being your Gateway/DAO/Repository/etc. will call into the Mapper before it returns, so you get a rich business object versus the underlying data container.

However, this seems to be related, if not identical, to the Factory pattern (in the DDD parlance, anyways), which constructs and returns a domain object.  Wikipedia says this re: the DDD Factory:

Factory: methods for creating domain objects should delegate to a specialized Factory object such that alternative implementations may be easily interchanged.

From that quote the only difference I could think of is that the DDD-style Factory could be parameterized so it could return a specialized type of object if the need arose (e.g. BusinessCustomer versus ResidentialCustomer) while the "Mapper" is keyed to a specific class and only does translation.

So is there a difference between these two patterns or are they essentially the same thing with different names?

答:
Builders encapsulate complex business logic to build an object. Mapper on the other hand should just copy the fields from one to another.

For example map from Database Employee Object to Domain Employee Object, map from Domain Employee Object to Client Contract.

Builders on the other hand host multiple business decisions to build an object. From Single Responsibility point of view, this makes sense.


问:
What is the most inspiring speech from a developer you ever watched?
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)

答:
Steve Jobs' commencement speech at Stanford, 2005

http://www.youtube.com/watch?v=D1R-jKKp3NA

3 stories...


问:
When to use primitive vs class in Java?
I see that Java has Boolean (class) vs boolean (primitive).  Likewise, there's an Integer (class) vs int (primitive).  What's the best practice on when to use the primitive version vs the class?  Should I basically always be using the class version unless I have a specific (performance?) reason not to?  What's the most common, accepted way to use each?</p>

答:
In Item 5, of Effective Java, Joshua Bloch says

The lesson is clear: prefer primitives to
  boxed primitives, and watch out for unintentional autoboxing.

One good use for classes is when using them as generic types (including Collection classes, such as lists and maps) or when you want to transform them to other type without implicit casting (for example Integer class has methods doubleValue() or byteValue().

Edit: Joshua Bloch's reason is:

```<code>// Hideously slow program! Can you spot the object creation?
public static void main(String[] args) {
    Long sum = 0L;
    for (long i = 0; i < Integer.MAX_VALUE; i++) {
         sum += i;
    }
    System.out.println(sum);
}
</code>```

This program gets the right answer, but it is much slower than it should be,
  due to a one-character typographical error. The variable sum is declared as a Long instead of a long, which means that the program constructs about 2^31 unnecessary Long instances (roughly one for each time the long i is added to the Long sum). Changing the declaration of sum from Long to long reduces the runtime from 43 seconds to 6.8 seconds on my machine.

Title: When to use primitive vs class in Java?

Body:
In Item 5, of Effective Java, Joshua Bloch says

The lesson is clear: prefer primitives to
  boxed primitives, and watch out for unintentional autoboxing.

One good use for classes is when using them as generic types (including Collection classes, such as lists and maps) or when you want to transform them to other type without implicit casting (for example Integer class has methods doubleValue() or byteValue().

Edit: Joshua Bloch's reason is:

// Hideously slow program! Can you spot the object creation?
public static void main(String[] args) {
    Long sum = 0L;
    for (long i = 0; i < Integer.MAX_VALUE; i++) {
         sum += i;
    }
    System.out.println(sum);
}

This program gets the right answer, but it is much slower than it should be,
  due to a one-character typographical error. The variable sum is declared as a Long instead of a long, which means that the program constructs about 2^31 unnecessary Long instances (roughly one for each time the long i is added to the Long sum). Changing the declaration of sum from Long to long reduces the runtime from 43 seconds to 6.8 seconds on my machine.


问:
Do CS departments have formal procedures to choose languages taught?
I'm not talking about countryside colleges/unis.

Are there any thought-out procedures in top-ranking institutions based on formal criteria, actual statistics or demand from the industry?

If so, what are the criteria used?

Are the decisions to drop certain languages and introduce others made systematically or in a haphazard manner?

答:
If we're talking about, say, top 10 ranked US colleges and universities (other countries will likely have different traditions and people will have wildly different definitions of a "countryside college or university"), no.  A community college will generally choose what languages to teach based on what languages employers in the geographic area served by the college use.  The top-ranked universities, on the other hand, generally have much more idiosyncratic criteria.  For example, when I went to MIT, the primary languages used were Scheme (because professors Abelson and Sussman wrote Structure and Interpretation of Computer Programs) and CLU because Prof. Liskov designed it.  Neither of these have ever been particularly useful languages for professionals though LISP, at least, has some users in academic fields like AI.  The top-ranked universities see themselves as teaching computer science, not programming, and since they generally assume that you'll use many different languages over your career, the particular languages that get taught are not particularly important.  Community colleges are in the business of teaching programming so they generally prefer languages that are in more common use.

From time to time, universities do change the languages they teach.  That's generally going to involve a lot of faculty meetings and discussions but it's hard to know whether that would qualify as "systemic" or "haphazard" in your definitions.  In general, the criteria will be pedagogical, not practical.  That is, the professors are much more likely to care about what languages make teaching the underlying concepts easier and what languages they view as promoting beautiful code rather than what languages employers demand.


答:
```<code>return ($this->main->context != "ajax" || in_array($this->type, $this->definition->ajax)) ? eval('return method_exists($this,"Show'.ucfirst($this->type).'") ? $this->Show'.ucfirst($this->type).'('.(count($args) ? join(",",array_map(create_function('$a','return (is_numeric($a) || preg_match("/^array/",$a)) ? $a : "\"".$a."\"";'),$args)) : "").') : null;') : '';
</code>```

I bumped into this code on a project I inherited some time ago. I think it nicely demonstrates why it is a bad idea to try and use as few lines as possible. It's completely unreadable and impossible to debug.

Title: Is fewer lines of code always better?

Body:
return ($this->main->context != "ajax" || in_array($this->type, $this->definition->ajax)) ? eval('return method_exists($this,"Show'.ucfirst($this->type).'") ? $this->Show'.ucfirst($this->type).'('.(count($args) ? join(",",array_map(create_function('$a','return (is_numeric($a) || preg_match("/^array/",$a)) ? $a : "\"".$a."\"";'),$args)) : "").') : null;') : '';

I bumped into this code on a project I inherited some time ago. I think it nicely demonstrates why it is a bad idea to try and use as few lines as possible. It's completely unreadable and impossible to debug.


答:
Usually I go with the primitives. However, one peculiarity of using classes like Integer and Boolean is the possibility of assigning null to those variables. Of course, this means that you have to do null checks all the time, but still better to get a NullPointerException than to have logic errors due to using some int or boolean variable that has not been initialized correctly.

Of course, since Java 8 you can (and probably should) go one step further and instead of e.g. Integer you could use Optional<Integer> for variables that might or might not have a value.

Additionally, it introduces the possibility to use null to assign those variables an "unknown" or "wildcard" value. This can be handy in some situations, for example, in Ternary Logic. Or you might want to check whether a certain object matches some template; in this case you can use null for those variables in the template that can have any value in the object.

Title: When to use primitive vs class in Java?

Body: I see that Java has Boolean (class) vs boolean (primitive).  Likewise, there's an Integer (class) vs int (primitive).  What's the best practice on when to use the primitive version vs the class?  Should I basically always be using the class version unless I have a specific (performance?) reason not to?  What's the most common, accepted way to use each?</p>

ContentLicense: CC BY-SA 4.0


问:
How to continue development without the webservice?
We make iOS apps where we often get data in a list from an API, then we select the data and go to the next ViewController.

Often it happens that the server is down or some API is not ready.

What is a good development practice where we can continue our regular work flow without depending on the webservice and then when its ready without making much changes continue using the web-service and till then use some fixed data.

答:
Since you know how the API will be accessed, and what types of values will be returned, you could create your own basic version of the API that just does something basic with your input and returns something like what would be expected. Then when the API is ready you can just swap it in.

Afraid I can't provide any detailed instructions for how this would be achieved for iOS, as I am not familiar with iOS development. However, I have worked on a project where one set of developers was working on the front end in one country and a separate company in a different country was working on the web service. The UI developers were accessing a basic javascript library that just returned test data, and the back end developers were passing in values to the service with a very basic test harness. There were a small number of issues to be ironed out when the two were put together but altogether it worked quite well.


问:
Career advice: stay with PHP or start a new career in something else ( .Net?)
I'm planning on moving to NY in 6-12 months tops, so I'm forced to find a new job. When I'm planing to start my life in another city it's also probably a good time to think about career changes.

I've found a lot of different opinions about PHP vs .Net vs Java and this is not the topic here. I don't want to start a new fight about which language is better. Knowing a programming language is not the most important thing for being a software developer. To be a really good developer you need to know OOP, design patterns, testing... and a language is just a tool to make things happen.

So back to my question. I have mixed experience in IT - 1 year as an IT support guy (Windows administration and support), around 2 years of experience in embedded programming (VB.Net 2005) and for the last 2 years I'm working with PHP/MySQL. I have worked with Magento web shop, assisted in some projects in Symfony, modified few Drupal sites.

My main concerns are the following:

Do I continue to improve my skills in PHP e.g. to start learning some major PHP framework like Zend, Symfony maybe get some PHP certification.

Or do I start learning .NET or Java. I'm more familiar to .NET so I'll probably choose it if choice falls between .NET and Java ( or you could convince me to choose Java :).

Career-wise, I don't know what is the best choice. Learning a new framework and language is more time consuming then improving my existing skills in PHP. But with .NET you have a lot of possibilities (Windows 7 Phone development, Silverlight, WPF) and possibly bigger chances to find better jobs.

PHP jobs are less well payed then .NET, at least, according to my research (correct me if I'm wrong). But if I start now with .NET I'm just a beginner and my salary will be low. I need at least 2+ years of experience in some language to even try to find some job that is paying higher than $50-60k in NY. My main goal in the next 2-3 years is to try to find a job in the $60-80k category. Don't get me wrong, I'm not just chasing money, but money is an important factor when you're trying to start a family.

I'm 27 years old and I feel that there isn't a lot of room for wrong decisions regarding my career, so any advice will be very welcome.

Update

Thank you all for spending time to help me with my problem. All of the answers and comments have been very helpful. I have decided to stick with PHP but also to learn C# and Silverlight 4. We'll see where the life will take me.

答:
I hate to seem like a troll, but the language you should learn is English.  There are a bunch of errors in your post and that just looks sloppy.  If I were hiring and that was your resume, I wouldn't care what programming languages you said you knew, I would assume that your sloppiness with the English language would carry over to your programming work.

It didn't appear that you are coming at English as a second language (I could, of course, be wrong) but there were enough grammatical and spelling errors to give most hiring managers pause.  Since they are only going to see your written word at first, you need to get that fixed.


问:
Shouldn't documentation be written together with tests rather than in the code?
It is popular to write documentation in the same file as the code and extract that using software to generate documents. In order to not affect performance, the documentation is written within commented lines, in a DSL designed just for the purpose of that. And that often results in cumbersome source file.

Nowadays, test driven development is popular, and usually tests are written on separate files from the code. Since test files are not run during production, it does not interfere with performance, and hence test are not written within commented lines in a DSL, but are written in the same programming language as the code.

Doesn't it make more sense to write documentation in the same file as tests not in commented lines but in the same programming language using DSL? For each syntactic element like class, method, first a documentation telling the features of it can be written, and then test can follow it. That would make things nicer in my opinion.

I have scripting languages like Ruby in mind if that makes difference.

答:
It is popular to write documentation in the same file as the code and extract that using a >software to generate documents.

Yes, that is popular - for software libraries and their documentation. I guess you are talking about that kind of docs (and not, for example, user manuals).

And that often results in cumbersome source file.

Well, that is quite debatable. When done with care, IMHO the documentation is exactly where it belongs - in eyesight of the thing it describes, so when I look at a method signature or implementation, I have also to short description of the intensions of that method at hand.

Doesn't it make more sense to write documentation in the same file as tests not in commented lines but in ordinary language using DSL?

I see some problems here:

in your docs, you typically want a general outline of your class, and a description for each public method or property of your class. So the docs follow in structure exactly your classes structure, but your tests have typically a different structure. For a specific method, you will typically have more than one test, for a class you will have a lot tests and for a property you might have no test at all.

when you place the docs not directly above a method, you will have to repeat the complete method signature and function name at the docs place, to make the description readable - so this leads to some form of unwanted code repetition. Placing the doc above the method avoids that.

docs nearby the documented function have the highest chance to be kept up with the code when something is changed. When you put your docs somewhere else, you lower that chance significantly.

So my answer is - no, I don't like that idea (but I like the question, so +1 for that).

What I like, however, is the idea of using tests as part of the documentation (not the full documentation, they are the examples part, but don't describe the general requirements). The documentation could give references to specific tests showing example behaviour, and a doc extraction tool could use that references to create a formatted document where those examples are included (don't know if such a tool exists, but perhaps this would be a nice new feature for one of the available products).


答: This speech is my current favorite.  It's Why the Lucky Stiff's talk at the Art && Code Symposium discussing the problems with the way we currently teach programming.  I will admit it might not be the best or most inspiring speech on the list, but I believe the story of _why brings it to another level.</p>

Title: What is the most inspiring speech from a developer you ever watched?

Body:
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)


问:
What benefits are there to native JavaScript development?
Given how much simpler jQuery development is, when compared to native JavaScript, what makes people forgo libraries like jQuery altogether?

Is this because jQuery has limitations or it is slow? I mean, if jQuery is so easy compared to native javascript, what reasons do people have to still use pure javascript?

答:
I would say the main issue is that more and more people (the vast majority?) do not know how to code in JavaScript anymore. If jQuery can't do something, they can't do it.

It's getting to the point that plain javascript examples are becoming hard to come by. Nothing against jQuery; it's a great framework. I got a lot of good ideas from it, but people should learn JavaScript first and then learn a framework. I personally find my own framework more flexible and better suits my needs, and yes I do reinvent the wheel sometimes but the total control and having control over bug fixes is a huge benifit provided your willing to put the work into learning JavaScript.

Not only that. Knowing vanilla JavaScript makes it a lot more fun to play around and experiment with the newer features instead of waiting for a framework-based implementation. Also, I don't blame jQuery for this as it's mainly a DOM library, but it can be a pain to scale with large projects. Other frameworks do a better job at this; Prototype comes to mind.

In short, it's a great framework, but not the be-all end-all people make it out to be.

OwnerDisplayName: Mike


答:
Most colleges that I know of teach Java as the introductory language. Talking to one of my professors about how our department chose that language (and why it can't be replaced by something else), he said:

Java is portable. Write once, run everywhere.

It's strongly-typed

It's a managed language (most first-year CS students get very confused with pointers)

It's old, which means there are plenty of resources for it

It shares a C-like syntax, making it broadly applicable

Getting a basic working program in Java takes very little time and code

He said that there are no other languages that provide those benefits in such a way to provoke the department to change. I argued for C#, but he contended that it's not truly portable and even though .NET has far better support for things like generics, it's not enough to prompt a change.

Title: Do CS departments have formal procedures to choose languages taught?

Body:
I'm not talking about countryside colleges/unis.

Are there any thought-out procedures in top-ranking institutions based on formal criteria, actual statistics or demand from the industry?

If so, what are the criteria used?

Are the decisions to drop certain languages and introduce others made systematically or in a haphazard manner?


问:
Scrum: How much can the Product Owner shake up the Product Backlog?
For the last 3 sprints or so, I've observed our Product Owner suddenly shoving new stories -- stories not previously in the Product Backlog -- at the top of the Product Backlog.

Because of this, the existing items in the backlog never get worked on.  New stories continuously take over the helm and make into our Sprint Backlog.

My question is - how much can the Product Owner really shake up the Product Backlog?  Is it really fair game to ignore what's already in the backlog and keep on shoving new stories at the top?

I've tried to argue that this is hogwash, but I often hear counter-arguments such as "adapting to frequently changing business needs," "we're moving so fast - we're super agile" and I don't know what to say to those arguments, although I feel it is not how Scrum was meant to be.

EDIT:
I understand that the product owner owns the product backlog.  What I am observing at my team though, is that the PO constantly puts new items at the top of the backlog, ignoring the existing backlog items completely.

For instance, say we're building a car and PO creates 10 stories to make it happen.  We decide to take on 3 stories in our sprint backlog - thus 7 stories still remain in the product backlog.  Everything is good so far.

At the next sprint planning, however, the PO now claims that we need to build a baseball bat and creates 5 stories around that - which are then placed at the top of our backlog (i.e. highest priority); nevermind those car stories we already had in the backlog.

答:
```<code>> how much can the Product Owner really shake up the Product Backlog?
</code>```

It is the job of the Product Owner to "shake up the Product Backlog".

In Scrum it is the job of the product owner to  rank and prioritize the features in the Product_Backlog.

product owner and team agree what to implement in the next sprint and put these features into the Sprint_Backlog

You as a developer have to argue if you need technical features in the sprint log that the product owner doesn't see.

Body:
> how much can the Product Owner really shake up the Product Backlog?

It is the job of the Product Owner to "shake up the Product Backlog".

In Scrum it is the job of the product owner to  rank and prioritize the features in the Product_Backlog.

product owner and team agree what to implement in the next sprint and put these features into the Sprint_Backlog

You as a developer have to argue if you need technical features in the sprint log that the product owner doesn't see.


答:
how much can the Product Owner really shake up the Product Backlog?

As much as he likes.

It is the "Product Owners" job to represent the user and get them what they want.

Is it really fair game to ignore what's already in the backlog and keep on shoving new stories at the top?

Sure is.

If the old stories are no longer relevant to the user why build them. You only want to build what is important to the user. But be careful. A story is supposed to be a user action. You should be able to describe a story in terms of an action a user does (no technical details).

I've tried to argue that this is hogwash

It is the job of the "Scrum Master" to protect the developers from flippant change.

It is the job of the "Scrum Master" to pick what makes it into the sprint and protect the developers from the "Product Owner" and make sure the technical part of the project work. This means he should be picking items to form the architecture first. He should try and deliver some user stories but the ones that make sense (trying to respect the Product Owners priority but he does not need to stick to it 100% if that does not make technological sense).

Note: As pointed out below my definition of "Scrum Master" here may not be fully standard. I was simply using it to point out that it is not the Job of the PO to pick tasks for the scrum backlog as this is a technical in nature (and the PO being a chicken has no voice in the sprint planning). It is the job of the team to pick what goes in the sprint backlog as they are technically inclined and understand how components will interact. They will be heavily influenced by the priority in the product backlog but that is not there only consideration they use when making technical decisions. My use of the term "Scrum Master" is heavily influenced by my experience where the "Scrum Master" is usually the technical or team lead (usually a senior dev with the clout/fortitude to stand up to management who tend to be pushy when they can get away with it) this of course is not required by scrum.

-

but I often hear counter-arguments such as "adapting to frequently changing business needs," "we're moving so fast - we're super agile" and I don't know what to say to those arguments,

These are good arguments. But make sure

You are talking about true stories

Your architecture takes priority over user interface

although I feel it is not how Scrum was meant to be.

Scrum is meant to allow you to react quickly.

But during a sprint there should be no change to the sprint backlog. And make sure your sprints are of reasonable length: 3 to 4 weeks. That should give you a chance to finish a reasonable small story or build the foundation for a large story.

Title: Scrum: How much can the Product Owner shake up the Product Backlog?

Body:
For the last 3 sprints or so, I've observed our Product Owner suddenly shoving new stories -- stories not previously in the Product Backlog -- at the top of the Product Backlog.

Because of this, the existing items in the backlog never get worked on.  New stories continuously take over the helm and make into our Sprint Backlog.

My question is - how much can the Product Owner really shake up the Product Backlog?  Is it really fair game to ignore what's already in the backlog and keep on shoving new stories at the top?

I've tried to argue that this is hogwash, but I often hear counter-arguments such as "adapting to frequently changing business needs," "we're moving so fast - we're super agile" and I don't know what to say to those arguments, although I feel it is not how Scrum was meant to be.

EDIT:
I understand that the product owner owns the product backlog.  What I am observing at my team though, is that the PO constantly puts new items at the top of the backlog, ignoring the existing backlog items completely.

For instance, say we're building a car and PO creates 10 stories to make it happen.  We decide to take on 3 stories in our sprint backlog - thus 7 stories still remain in the product backlog.  Everything is good so far.

At the next sprint planning, however, the PO now claims that we need to build a baseball bat and creates 5 stories around that - which are then placed at the top of our backlog (i.e. highest priority); nevermind those car stories we already had in the backlog.

OwnerDisplayName: Loki Astari


问:
URL Naming Convention with Repetitive Letter
What is a good practice to name an URL if it contains repetitive letters. For example, /info/foossite

The two s looks kind of odd and if this was access point for a Web-Service, this could lead into misspelling. In most programming languages, we have Camel notation. However, as URLs are case insensitive, we don't have that luxury here.

So, what is the best practice in this regard?

答:
HTTP URIs are not case-insensitive. The host is case-insensitive, but the path is case-sensitive (see STD 66). Check these two HTTP URIs, for example:

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

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

You’ll find that they represent different pages.

So you could use camel case URIs, e.g. example.net/FoosSite. (Note that maybe some servers, probably those running on Microsoft operating systems, treat all HTTP URIs as case-insensitive by default, so you’d have to check their documentation.)

But in my opinion there is no need for camel case. If your path contains several words, you <s>should</s> could use a delimiter of some kind. Probably most popular is -. Wikipedia uses _. You can find many discussions about which delimiter to use for SEO and usability. See for example this (closed) question or an (older) blog post by Matt Cutts (who is working for Google).


问:
How do you stay focused at work?
Sometimes, the things I have to do for my job are interesting and engaging.  Sometimes, they aren't.  Occasionally, they really aren't.

Do you have any particular strategies or tricks for dealing with those dull stretches when your brain would rather be doing anything other than what you're supposed to be doing, particularly when the Internet and its boundless opportunities for interesting Slack beckon?

答: Try to get into "flow state". It can often be hard, so you should reduce distractions as much as possible. If you are tired, do some exercise - it will wake you up.</p>

Title: How do you stay focused at work?


问:
Developing With Ruby/Rails Easier, Faster Than Developing With PHP/CakePHP?
What is your experience when developing web applications using one of these two languages/frameworks? Which have you found to be more convenient and faster to develop with?</p>

答:
Either would be perfectly fine for developing web applications.

If your stronger in PHP than Ruby, then likely Cake would be "faster" because you wouldn't have to spend the extra time familiarising yourself with Ruby syntax. Obviously the converse is true.

I don't have a huge amount of experience of either but I'd say I prefer Ruby because I find the libraries easier to use and install (rvm/gems etc) and I like having a local development server rather than using Apache and the large and vocal open-source community on github/blogs/twitter is mostly a good thing.

Really, who cares, they're basically the same: Dynamic scripting language, MVC framework... If you're looking to expand your knowledge you might as well look at something very different like node.js or Haskell and Snap.


问:
Why it is not recommended to post several defects in the same issue / ticket?
I am not sure if this is the place to ask the following conceptual question (Stackoverflow is definitely not).

I saw this question in a multiple choice exam (single answer), similar to the ISTQB exams:

Why it is not recommended to report several defects in the same issue
  / ticket ?

a. In order to keep the report concise and clear.

b. Because the developers might fix only one bug.

c. Because the testing group testers are rated by the amount of bugs
  they find.

d. Bugs management systems does not support this feature of multiple
  bugs.

My sole opinion is that a is the correct answer.

b - can't be it as the fix-feedback-resolved-closed should avoid that case.
c - Obviously wrong.

d - Redmine / Trac plugins supports multiple fields.

The answer according to the answer sheet is b.

Can someone explain why ? Comments with opinion about answers are welcome.

答:
Look at it from the perspective of someone else using the system, showing up a few months later.  They find a bug in the program. They Google around and see that there's a support ticket that matches they problem they're having.  And hey, it's closed! Awesome! It's been fixed in the latest version!  So, they update... and the bug's still there?  What's wrong with these stupid developers?!?

Nothing, actually. Turns out there's something wrong with the person submitting the bug report. They submitted two bugs in the same ticket. One was easy to fix, and got fixed quickly, and the other wasn't.  Even if you use something like fix-feedback-resolved-closed, it can still be less than clear what's going on, especially to an outside observer.

It's much better to give each bug its own ticket, and if you have multiple bugs that are related but apparently distinct, most bug tracking systems have a feature that lets you link one bug to another.  (And if not, you can just put it in the report. "See also bug #12345.")


答:
Imagine if Stack Overflow had a guideline: instead of asking one question, you come and ask, in the same question, whatever comes into your mind, all your issues you had for the last two weeks. What would upvote and downvote mean? What would be the titles of the questions? How to accept the best answer? How to tag the question?

Bug tracking system is done to... track bugs. Tracking a bug means:

Creating a record saying that a bug might exist, with information about how to reproduce it,

Confirming that indeed, the bug exists and is a bug, not something by design,

Asserting that the bug is now solved,

Confirming that the bug was solved.

In a very simplistic model, 1 and 4 will be done by the customer, and 2 and 3 – by the developer.

Imagine the following log:

Day 1 [Customer] When pressing on “Remove” button in “Product details” window, the application hangs. Restarting the application shows that the product wasn't removed. The expected behavior is to remove the product.

Day 4 [Developer] <Issue reproduced>

Day 5 [Developer] <Issue solved in revision 5031>

Day 12 [Customer] <Ticket closed: issue solved>

The log is simple and clear. You can easily track what was done and when, which revision solved which bug, etc. For example, if the bug tracking system is integrated with the version control, when you view a specific revision, you can check what bugs were solved in it.

It's easy to find information. It's easy to see its state (is it reproduced? If the ticket was closed, why?). It's easy to filter tickets (I want to display tickets which concern only the UI of the plugins, given that I want only tickets which are open, older than one week and assigned to me by our interaction designer and are medium or high priority).

It's easy to reassign a ticket or to originally determine which is the person who should be in charge of the bug.

Now imagine the following log:

Day 1 [Customer] The app hangs when I press “Remove” button in “Product details” window. Also, the background color of the left panel is dark blue, while it should be purple. I also noted that the text of the “Product details” window is not translated well to German; is it expected? When the final translation would be available? BTW, have you received the new icon I sent for the “Publish product” action? I don't see it in the “Sync data” window.

Day 6 [Developer] I changed the color to purple.

Day 7 [Developer] Yes, it's normal that the translation to German is incomplete.

Day 8 [Customer] Ok for German. What about Italian? Lucia sent you the XML file two days ago.

Day 9 [Developer] It's ok now.

Day 10 [Customer] Ok for the “Remove” button? Strange, at my computer, it still hangs.

Day 11 [Developer] No, I wanted to say it's ok for Italian translation.

Day 12 [Customer] I see. Thank you. But there is a problem with the color. You changed it to dark purple, but it should be light purple, like the top panel on the main window.

Day 13 [Developer] I updated the icon.

Day 14 [Customer] The icon? What icon?

Day 15 [Developer] The icon you asked me to update.

Day 16 [Customer] I never asked you to update any icon.

Day 17 [Developer] Of course you asked. See this ticket. You wrote that the publish product icon should be updated. I've done it.

⁞

Day 100 [Customer] So, what about the entries in the log?

Day 101 [Developer] I have no idea what you're talking about. It's not even in this ticket, but in 6199. I'm closing this one as solved. <Ticket closed: issue solved>

Day 102 [Customer] Sorry to reopen it, but the problem is not solved. I'm talking about the entries in the log: I told you last week that the text is sometimes invalid when it contains unicode characters. Do you remember? <Ticket reopened>

Day 103 [Developer] I vaguely remember something like that, but after searching the last three pages of this ticket, I can't find any trace. Can you write again what was the problem?

⁞

Day 460 [Developer] I spent two hours searching for a trace of what you've said about the files sent encrypted through the network. I'm not sure I can find the precise request.

Day 460 [Customer] You guys should really be more organized. I notified you four times about this issue for the last two weeks. Why are you forgetting everything?

⁞

What's this log about? It was solved 43 times and reopened 43 times. Does it mean that the developer is so stupid that he can't solve the same issue for 460 days? Ah, no, wait, this ticket was assigned to 11 developers meanwhile. What's the deal? How to search for a specific issue? It's actually assigned to Vanessa, but her five colleagues are concerned as well by seven of the eleven issues in this ticket. When the ticket should be closed? Is it when half of the issues are solved? Or maybe ten out of eleven?

Note: You may believe that such logs don't exist. Believe me, I've seen ones more than one time.

Title: Why it is not recommended to post several defects in the same issue / ticket?

Body:
I am not sure if this is the place to ask the following conceptual question (Stackoverflow is definitely not).

I saw this question in a multiple choice exam (single answer), similar to the ISTQB exams:

Why it is not recommended to report several defects in the same issue
  / ticket ?

a. In order to keep the report concise and clear.

b. Because the developers might fix only one bug.

c. Because the testing group testers are rated by the amount of bugs
  they find.

d. Bugs management systems does not support this feature of multiple
  bugs.

My sole opinion is that a is the correct answer.

b - can't be it as the fix-feedback-resolved-closed should avoid that case.
c - Obviously wrong.

d - Redmine / Trac plugins supports multiple fields.

The answer according to the answer sheet is b.

Can someone explain why ? Comments with opinion about answers are welcome.