答:
Choosing between a library and an executable file is relatively simple: does it make sense to execute the code you want to put into an executable as a standalone program? If not, it should probably be a library. In general, I would favour a thin executable layer over as many libraries as needed, since that makes it easier to reuse those backend libraries later and they are not tied to a particular program.

Far as deciding on how to split your code between libraries goes, you might find Uncle Bob Martin's article on granularity useful.

In it he talks about OO structure and defines several principles that can help you package your code appropriately. These are also covered in more detail in his book, Agile Principles, Patterns, and Practices in C#.

I will summarize the principles below:

The Reuse/Release Equivalence Principle (REP)

The granule of reuse is the granule of release. Only components that are released through a tracking system can be effectively reused. This granule is the package.

Uncle Bob defines reuse as being able to statically or dynamically link the reused library into his program and never having to look at its source code. When a new version of the library is released, he can just integrate it into his system.

Treating libraries this way drives only keeping related things together in the same package. Otherwise, the library's consumers might have to upgrade to a new version for no reason or lag a few versions behind.

The Common Reuse Principle (CRP)

The classes in a package are reused together. If you reuse one of the classes in a package, you reuse them all.

This principle supports the one above. If you have classes in the same package that aren't related to one another, you may be forcing the users of your library to upgrade unnecessarily.

The Common Closure Principle (CCP)

The classes in a package should be closed against the same kinds of changes. A change that affects a package affects all the classes in that package.

This principle talks about maintainability. The idea here is to group classes based on how they might need to change. That way your changes can be localized to one part of the application and not spread all over.

The Acyclic Dependencies Principle (ACP)

The dependency structure between packages must be a Directed Acyclic Graph (DAG). That is, there must be no cycles in the dependency structure.

Disallowing cyclic dependencies allows each package to be developed independently and "released" to the rest of the company when new changes are ready. This way you don't end up with two teams deadlocked, waiting on each other to finish some work.

Title: How do you decide where functionality should belong in a large-scale project?

Body:
In my current development situation, we have a lot of DLLs, executables, and static libraries. How do you decide what should go into a DLL? What should go into an executable? Why have separate functionality in different executable files? I'm hoping the answer will be concise, but this is a largely opinionated topic it would seem.

How do you decide where functionality resides in a large-scale project (more than one executable file)? I'm expecting answers to range from, "Good Design" to "Modularity" to "Whatever management puts in a requirements doc".


问:
Should a function use premature returns or wrap everything in if clauses?

Possible Duplicate:

  Where did the notion of “one return only” come from?

Which is better? I see pros and cons for both, so I can't really decide on which one to stick to.

Wrap in if clause

```<code>function doIt() {
   if (successfulCondition) {
      whenEverythingGoesWell();
   }
}
</code>```

Pro: Shows programmer's intention through indentation.

Con: Indentation can get really deep if you need to short circuit many times. For example, doThirdThing() requires the success of doSecondThing(), which in turn requires the success of doFirstThing(). This happens a lot in web development where many web services are not reliable.

Premature return

```<code>function doIt() {
   if (!successfulCondition) {
      return;
   }
   whenEverythingGoesWell();
}
</code>```

Pro: Subversion checkins would be succinct. Sometimes, I see co-workers wrap super long functions in an if clause. The whole shebang gets checked in and makes reading Subversion diffs difficult.

Con: Requires you to read the whole function to figure out the various run paths.

答:
Oh dear, this has been the subject of university courses on program purity, and corporate coding standards, since about the time that Adam was a little tiny chap.

The major reason for a single point of return is that it means you don't have to hunt the source trying to find hidden exits (or so it is claimed).

What this actually means is you can be lazy when reading the source.

Now, the idea of being lazy when reading the source is the you can only concentrate on the bits that you think  "matter". Whatever that is.

Trouble with all this is, the use of single returns can make the program / function flow and coding extremely convoluted. (Reminds me of code I wrote years ago where a function grew by 10 lines of VERY obscure and horrible code in order to avoid a "goto").

Sometimes, doing "naughty" things is right because it makes the result simpler and easier to understand. So if this means using the occasional goto, or using multiple returns, then you do so. But only when the alternative is worse. This can require some careful thought and might be a bit of a judgement call.

These days I tend to use multiple returns pretty much as a matter of course. The reason is that the "lazy" approach to reading code generally gets you nowhere. You DO need to read a function / method from the start to the end, so the multiple returns are pretty apparent - and doubly so if you put big comments in against each (which I do). So the lazy argument really does not hold water.

Nitpickers corner: Just because I mention gotos does not make me a cowboy or nutcase. I think I've managed to use "goto" twice in about the last 25 years. The point still stands, though: If its the best solution, use it.

ContentLicense: CC BY-SA 3.0


答:
Personally I have found the first way (which you have titled "Wrap in if clause") to be my preferred way. If I need to mitigate your con about deep indentation, I simply use a Boolean flag to keep track if doFirstThing() completed successfully. For me, it is all about code readability. I find it hard to track down multiple returns, as opposed to dealing with a little further indentation.

However, some situations might call for a greater level of performance, and therefor would benefit from a "Premature return". In those situations you would have another pro and con to weigh.

You decision should be based on: 1. What makes the code easiest to read?; 2. How important is optimization for performance? I cannot give you a single answer because other d other details about your usage are needed.

Title: Should a function use premature returns or wrap everything in if clauses?

Body:
Possible Duplicate:

  Where did the notion of “one return only” come from?

Which is better? I see pros and cons for both, so I can't really decide on which one to stick to.

Wrap in if clause

```<code>function doIt() {
   if (successfulCondition) {
      whenEverythingGoesWell();
   }
}
</code>```

Pro: Shows programmer's intention through indentation.

Con: Indentation can get really deep if you need to short circuit many times. For example, doThirdThing() requires the success of doSecondThing(), which in turn requires the success of doFirstThing(). This happens a lot in web development where many web services are not reliable.

Premature return

```<code>function doIt() {
   if (!successfulCondition) {
      return;
   }
   whenEverythingGoesWell();
}
</code>```

Pro: Subversion checkins would be succinct. Sometimes, I see co-workers wrap super long functions in an if clause. The whole shebang gets checked in and makes reading Subversion diffs difficult.

Con: Requires you to read the whole function to figure out the various run paths.


答:
Martin Fowler talks about "Replace Nested Conditional with Guard Clauses" refactoring and generally advocates the clarity of quitting early for bad parameters over putting the whole method in an else clause (and see also https://stackoverflow.com/questions/4887212/shall-i-use-guard-clause-and-try-to-avoid-else-clause., which mentions that the traditional case for only exiting at the end was partly for resource clean up).

I think it's fairly easy and expected when I find a return at the beginning of a function, but I occasionally miss them buried in the middle, so I avoid putting returns in the middle unless it's really ugly to avoid them.


答:
Premature return

Premature return is the way I recommend writing functions.  This makes it clear at the top of the function that if you have invalid parameters that it will terminate early and not process further into the function.  This also reduces cyclomatic complexity.

Coding Horror: Flattening Arrow Code

Jeff Atwood (above) describes excellent methods to reduce cyclomatic complexity.

```<code>function doIt() {
   if (!successfulCondition) {
      return;
   }
   whenEverythingGoesWell();
}
</code>```

Con: Requires you to read the whole function to figure out the
  various run paths.

This Con can and should very easily be rectified with minor refactoring.

Refactor your methods into small succinct functions which perform discrete operations.  This will turn your whenEverythingGoesWell function into a list of private function calls which will read like pseudoCode.

Example

```<code>function MugOfCoffee doIt(int param1, string param2) {
   if (!successfulCondition(param1, param2)
      return;

   boilKettle();
   getMilkFromFridge();

   getMugsFromCuppboard();

   if(userHasCream())
      pourMilkIntoMug();

   putCoffeeInMug();
   purHotWaterIntoMug();

   return new MugOfCoffee();
}

private bool successfulCondition(int param1, string param2)
{
   // Validation logic here
   return true;
}
</code>```

At least each of the function names represents a step in a larger method and reads like it would in pseudocode.  If the pourHotWaterIntoMug method changes it's loosely coupled from the doIt function and so will make it far far easier to read.

Body:
Premature return

Premature return is the way I recommend writing functions.  This makes it clear at the top of the function that if you have invalid parameters that it will terminate early and not process further into the function.  This also reduces cyclomatic complexity.

Coding Horror: Flattening Arrow Code

Jeff Atwood (above) describes excellent methods to reduce cyclomatic complexity.

function doIt() {
   if (!successfulCondition) {
      return;
   }
   whenEverythingGoesWell();
}

Con: Requires you to read the whole function to figure out the
  various run paths.

This Con can and should very easily be rectified with minor refactoring.

Refactor your methods into small succinct functions which perform discrete operations.  This will turn your whenEverythingGoesWell function into a list of private function calls which will read like pseudoCode.

Example

function MugOfCoffee doIt(int param1, string param2) {
   if (!successfulCondition(param1, param2)
      return;

   boilKettle();
   getMilkFromFridge();

   getMugsFromCuppboard();

   if(userHasCream())
      pourMilkIntoMug();

   putCoffeeInMug();
   purHotWaterIntoMug();

   return new MugOfCoffee();
}

private bool successfulCondition(int param1, string param2)
{
   // Validation logic here
   return true;
}

At least each of the function names represents a step in a larger method and reads like it would in pseudocode.  If the pourHotWaterIntoMug method changes it's loosely coupled from the doIt function and so will make it far far easier to read.


问:
What are the disadvantages of using/writting a .Net Custom Membership Provider?
Recently, I posted the following question on SO: https://stackoverflow.com/questions/7197337/using-asp-net-membership-provider-with-an-existing-user-database

As you may notice, I ended up answering my own question stating that it looked like writting/implementing a "Custom Membership Provider" was the way to go.

Literally, a few minutes later, I stumble across this question: https://stackoverflow.com/questions/7222306/simple-login-attempt-counter-using-mvc-3-and-ajax/7222407#7222407

I try to answer and get a comment back that .Net Membership provider is "terrible on many levels". I'll admit, this is the first time I'm using Membership provider but it sure looked slick to me.

I haven't seen anything that backs up the "terrible" claim so before I implement something "terrible", I was hoping to get some feedback from the community.

答:
They aren't as flexible as many people think on a quick read of the docs, but they have their place.

If you don't need control over the user tokens and only need to build a custom/extended user data or membership set or need to pull that data from a existing/different source they have their place.

If you want to alter more than that you are often better off replacing the httpmodule that runs one of the auth providers then you get all the control.  Most people I have encountered breaking things with providers made the wrong choice for their situation at this level.

Either way you get a properly populated context.user which allows you to continue using most asp.net based user functions.


问:
When to Use workflow engines?
I've worked in past on some of the workflow engines as programmer but never had a clarity on why we chose the work-flow engines in first place. And as programmer I know that there are at least 100 ways to do anything when you are writing code but only few of the ways are the best!

I still don't understand which use cases are best solved by workflow engines (or rather their concept) than designing a good DI enabled application. I'm looking for any general characteristics of domain-neutral use cases, where work-flow engines are one of the the best options.

So my question is: What are general characteristics of a requirement which can be taken as a signal for opting for a good workflow engine and coding around it?

答:
IMHO the ONLY case where you should use this sort of thing is when it can be configured by less valuable users.  If you can solve your problem by giving them a tool then going back to working on something else more important then use one.

If you still need to set it up for them then I would imagine you could think of 10 different way do get the same result with a tool you are familiar with and it will be a lot easier to support and customize.

Title: When to Use workflow engines?


问:
Is Razor or XSLT better for my project?
I'm in the early stages in the design of a system that will essentially be split into two parts. One part is a service and the other is an interface with the service providing data through something like OData or XML. The application will be based on the MVC architectural pattern. For the views, we are considering using either XSLT or Razor under ASP.NET.

XSLT or Razor would help to provide a separation of concerns where the original XML or response represents your model, the XSLT or 'Razor view' represents your view. I'll leave the controller out for this example. The initial design proposal recommends XSLT, however I suggested the use of Razor instead as a more friendly view engine.

These are the reasons I suggested for Razor (C#):

Easier to work with and build more complicated pages.

Can easily produce non-*ML output, eg csv, txt, fdf

Less verbose templates

The view model is strongly typed, where XSLT would need to rely on
convention, eg boolean or date values

Markup is more approachable, eg nbsp, newline normalization, attibute
value normalization, whitespace rules

Built in HTML helper can generate JS validation code based on DTO attributes

Built in HTML helper can generate links to actions

And the arguments for XSLT over razor were:

XSLT is a standard and will still exist many years into the future.

It is hard to accidentally move logic into the view

Easer for non programmers (which I don't agree with).

It's been successful in some of our past projects.

Data values are HTML-encoded by default

Always well formed

So I'm looking for aguments on either side, recommendations or any experience making a similar choice?

答:
Here is a basic syntax comparison

Razor

```<code>@foreach(var item in View.List) {
  <span>@item.Name</span><br/>
}
</code>```

XSLT

```<code>  <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="item">
    <xsl:for-each select="name">
      <xsl:value-of select="."/><br/>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>
</code>```

The data sources for the two examples

XML

```<code><?xml version="1.0" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="transform.xsl"?>
<list>
    <item>
        <name>List item one</name>
        <url>http://site.com/one</url>
    </item>
    <item>
        <name>List item two</name>
        <url>http://site.com/two</url>
    </item>
</list>
</code>```

C#

```<code>ViewModel.List = new[] {
    new Link {
        Name = "List item one",
        Url = "http://site.com/one"
    },
    new Link {
        Name = "List item two",
        Url = "http://site.com/two"
    }
};
</code>```

Title: Is Razor or XSLT better for my project?

Body:
Here is a basic syntax comparison

Razor

@foreach(var item in View.List) {
  <span>@item.Name</span><br/>
}

XSLT

  <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="item">
    <xsl:for-each select="name">
      <xsl:value-of select="."/><br/>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

The data sources for the two examples

XML

<?xml version="1.0" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="transform.xsl"?>
<list>
    <item>
        <name>List item one</name>
        <url>http://site.com/one</url>
    </item>
    <item>
        <name>List item two</name>
        <url>http://site.com/two</url>
    </item>
</list>

C#

ViewModel.List = new[] {
    new Link {
        Name = "List item one",
        Url = "http://site.com/one"
    },
    new Link {
        Name = "List item two",
        Url = "http://site.com/two"
    }
};


问:
What is a Ph.D. good for in the software industry?
I'm a self-taught programmer and have just started a computer science degree to supplement my knowledge and fill in the gaps.

However, I'm already debating the direction of my education. I want a 4 year bachelor's degree for sure, but after that, I'm not sure: Is it worth it to get an M.Sc? What about a Ph.D.? What opportunities do these degrees open up?

Currently my goal is to be a software developer, but there are a number of fascinating fields in the software industry and I'm certainly interested in investigating many of them. It is in this respect that I think a higher degree may be worth it -- even if it wouldn't necessarily help a career of software development.

So will it be worth it? Will grad school open doors?

答:
Getting a PhD does two things to you and it uses up 4 or more years. You will need to decide whether those two things are worth the time. First, it gives you some initials after your name. For the rest of time, people who see those initials will think "wow, you must be really smart!" (and often, they will say it out loud.) On a resume it will generally help you, though in some circumstances it might hurt you, with people thinking you're overqualified or an egghead.

Second, and more importantly in my opinion, is the changes in your brain and your attitude that happen over the course of the degree. You will end up knowing more about some small part of the world than any other person. You will stand in front of 3 or 4 people who are experts, sometimes world-renowned experts, and teach them about your work. When you walk in, those experts will be supervisor, examiner, "bosses" of a sort and when you walk out they will be your peers. You  will learn a lot about one corner of computer science and a lot more about yourself and your capabilities. You will be confident being "the expert" when required. And that changes everything.

Unless you know now you want to be a prof, or to join a particular research lab, it seems unusual to me that you could decide about the PhD before doing the undergrad work. Go do the undergrad, and make friends with some grad students. They will tell you all you want to know about the life of a grad student, the life of a baby prof, the job prospects when you're out, and more.

I don't regret the time I spent on my PhD. It has opened many doors for me. It has made me more memorable ("right, you're the woman with the PhD, aren't you?") and been an asset to some of my teams independent of my abilities or knowledge ("we have a PhD on our team!"). But the industry I joined then is not the industry you're joining now. Talk to people who are in the thick of it now and then make a decision as you finish the undergrad work.

ContentLicense: CC BY-SA 2.5


问:
Guidance choosing tools for developing cross-platform mobile app
I have no mobile application development experience, I don't even own a rich mobile device (I can send text messages with my cellphone :) I have strong web, .NET, and Java experience but am open to develop with any language / platform. I need to target at least iPhone, Android, and Blackberry devices. I am seeking some guidance on the right set of tools for developing an application targeting these devices given my requirement. An easy deployment model would be a big plus. I have some notion of the difference between native apps and mobile apps on devices, and the later seems like it may be a good choice in terms of cross-platform support and easy deployment, but I do need access to some device information.

I currently have a fairly simple Java Swing application which is backed by JSON web services. The application is launched automatically when a user logs into their computer via a login script (it's deployed on corporate-like network). The user is presented with some html formatted information, and they click a button to answer a question. That's about it!

Core Requirements

Must be able to get user identification information from the mobile device and send it to the server; the Swing client sends the Windows account and domain name.

Would very much like to retrieve the local date and time of the mobile device and send it to the server

Must be able to have the GUI workflow described previously: present content to user, user "clicks" a button to respond.

Must be able to communicate with the JSON web service; if needed, could use some other data encoding, but just need to be able to communicate over HTTP (unless things are very different in the mobile world and I don't know what I'm talking about!)

Nice to Have Requirements

Render HTML fragments for the content (if not possible, could strip it down to plain text)

Be able to "click" on a link to send an email someway for help / feedback

"Click" link to a web site with information on how well the user is responding to their questions; could also build this into the app if it is a mobile app.

Be able to build some kind of user options "dialog"

Render small pictures along with the content; currently the pictures are just http resources.

Thanks in advance!

答:
It looks like your needs are pretty limited in terms of access to the device itself. I would suggest one of the cross-platform, web-ish platforms. There's a couple of them out there, such as PhoneGap http://www.phonegap.com/.

See http://mashable.com/2010/08/11/cross-platform-mobile-development-tools/ for some other options, and to make sure it supports the platforms you require.


问:
What has been your experience with SQL CLR for complex business logic?
So I thought I had a perfect use-case for a CLR SQL Procedure. I've search the Net for perhaps a similar example where data is retrieved, records added and updated. I have not looked at a SQL CLR procedure for awhile, but since it was released in 2005 (some 6 years ago!) I would have hoped there were plenty of examples!

I'm considering it because I have to look at some data, run it through a bunch of procedural logic, update, and then get it back to the client. My thinking here is to get as close to the DB metal as possible, and use that hardware to make it happen quickly.

Is anybody using SQL CLR? If you have, what has been your experience with it?

p.s. originally posted on stackoverflow and moved here based on a comment.

答:
I have used SQL Clr procs and triggers with very good effect to help database performance in some cases.  There are situations where your TSQL logic is just going to run slow (full text search without FTS indexes), and there are some things you just can't do in TSQL (lookup a DNS address, map reduce, image processing, OCR, unzip a file, complex algorithms, etc).

I'm considering it because I have to look at some data, run it through
  a bunch of procedural logic, update, and then get it back to the
  client. My thinking here is to get as close to the DB metal as
  possible, and use that hardware to make it happen quickly

But that is not a scenario where I would recommend using them.  The other poster is correct that set theory almost always has a way to do what you want.

SQL CLR is not closer to the metal, you are running a full instance of .net clr inside your database.  If you have none right now, adding one will add a lot of RAM usage for that one proc.  If you have 20 then the cost is not so bad "per proc".

If you are trying to do all these calcs to get the data back to the client, then just do it on the client.  The client usually has close to 100% of their CPU available to them.  The server will never have anywhere near that for one user.

If you have truly central logic or complex business requirements that you don't want to put on every client, put that on the server.  Don't do simple CRUD operations in SQL Clr, it doesn't buy you anything usually.


问:
What percent of your college course work is unit-tested code?
As a college student do you write unit-test for the project code you write?  Do you know how to properly use TDD?  Have you been taught to use testing frameworks (jUnit for example)?

I've just recently heard that a major company's project team was delivering software to User Acceptance Testing group that had only 7% line code coverage for unit testing.  While that shocks me, it just tells me that this company's software engineering practice are immature.  However I wonder if they could just hire a few recent graduates and raise the bar on the teams practices - assuming that these newly minted programmers were trained in the best practices.

Are you 2008 - 2010 CS graduates using best practices of unit testing your code?

答: Just graduated recently with a degree in CS.  I can honestly say that besides material that was focused on testing, I was never required to turn in tests.  That doesn't mean I didn't write them though.  I wish my school had discussed testing more.  Testing, and source control.

OwnerDisplayName: David Koontz


问:
How do you answer the question, "where do you see yourself in 5 years?"
What do recruiters expect you to answer when they ask, "Where do you see yourself in 5 years?" Something like:

I want to improve my technical skills ... blah-blah-blah ... architect?

Is it just to check your ambitions and if you are not going to leave in a month?

答: It's actually a great question to ask a younger candidate to get a sense of whether they want to stay on the technical path ("be a senior individual contributor") or move into management ("supervising a department of 5-8 developers").  It's nothing to be uncomfortable about; just tell the person what your ambitions are.   There's no wrong answer.</p>


问:
Model-View-Controller and client-side concurrency responsibility
In a web application that has a significant ajax component, where is the best place for the client-side concurrency responsibility to lie?

We're trying to use MVC on both the server application (LAMP stack) and the client application (ajax, mostly jQuery and unobtrusive js).

On the server-side, our model throws an exception if it finds a concurrency conflict that it can't solve on it's own. Essentially, the model tracks a revision number and date/user of creation and update. If the object being saved is out of date (older revision than in the data store), it attempts a merge. If it fails, the controller handles the exception and initiates some kind of resolution workflow.

The issue is with the client application; since ajax runs requests asynchronously, the model doesn't necessarily have the latest version of the data, but only the controller would know that--it is responsible for handling the queue/polling. The original idea was to pass all the updates fetched from the server directly to the javascript models for handling the concurrency--problem being that the lack of exceptions in javascript limits us to making flow-control decisions in the model that way.

Is it a bad idea to move the merging/model-conflict-resolution into the javascript controller? Is there a better way to handle this without the controller getting to far into model land?

Flow of the page:

User loads page(ajax application) with initial models--the models are numerous and have many attributes.

Page polls server for updates every 10-15 seconds--this is for auto-save and getting updates from other users.

User edits models.

Any conflicts that arise after initial entry are resolved when the user clicks the "save" button at the bottom of the page.

答:
Not entirely clear on what you are doing. But here is what I am assuming, you are writing some kind of application with large number of users updating same values(like price of a stock) and you want to use MVC on the client stack(JS) to create an desktop application like feel.

Having concurrency control in the controller seems right. If it was me I would write the controller as a bunch of classes(functions) with extensive support for call back. If there was successful, call this, if it failed call this.

Then in the View, Ill call the controller functions with right call back functions.

Even though this will work, I feel the architecture is too complicated. Either keep the server as a model only communication(acquire lock on edit, update on save, release lock on success) or move everything to server and use JQuery ajax to just do all the work.


问:
How mature is FreeBASIC?
A friend of mine is considering using FreeBASIC in a critical production environment. They currently use GWBasic, and they want to make a soft transition towards more modern languages. I am just worried that there might be undetected bugs in the software. I see that their version number is 0.22.0, which indicates, that it is not quite mature yet. I also read this discussion, without being able to conclude. Also on their Sourceforge pages there is no indication of whether it is Alpha or Beta (which anyways is not a very good indicator). Does anyone have own experience about the maturity, ideas on how to judge the maturity, or know of companies using FreeBASIC in a critical production environment?</p>

答:
I hope it's not too late to dig up an old thread.

I have used FreeBASIC in an industrial environment for 5+ years, and have found it to be rock solid. It actually worked very well back around 0.1, with growing QuickBASIC compatibility, and has slowly grown to exceed those roots and become more "serious" but can be told to work in a near 100% QB compatible mode. Fairly large releases only see the version number go up by 0.01.

I suggest your friend takes the GWBASIC to MS QuickBASIC, which should be quite easy (I've done it before, isn't it designed for 100% compatibility?). FreeBASIC then gives you a '21st century' option to run natively as a 32 bit app should anyone feel the need. Otherwise with Windows 7 etc, you're stuck using a VM running DOS or something.

Title: How mature is FreeBASIC?


答:
My vote is for NOT doing premeture returns.

Why? Primarily maintainablity. Code paths are a pain and debugging someone elses (or my own) mess 6 months later is much is eaiser if you can break point the one line at the bottom of the method saying "regardless of the path, this is what I'm returning ... is that what is expected?".


问:
How do I make web-application development less frustrating?
I am fairly new to web-application development.  I just can't shake the feeling that it takes me forever to do anything of even remote complexity.  In c++ and java I could write the same applications in a matter of hours.

On the web debugging is painful (especially if complex json-ajax) is involved.  IDEs suck.  The languages let everything through without errors until it is doesn't work anymore and you are stuck looking for a bug without any error or warning to guide you (and no real good way to step through the program).

Can someone guide me to reading material and/or technologies that would help me find a way to stay sane when developing complex web-applications?

Perhaps the answer is to use a good framework (zend?).  At work we are not really using a framework except for database models generators and basic add/update/delete page generators.

答:
If you're not using Firefox and firebug already, you should do so. Firebug's debugger is just full of awesomeness (not that Chrome's isn't, they're largely the same), but I tend to go with Firefox because of OS projects such as mozrepl, which allows you to script Firefox rather than using browser-spawning automated test suites such as Selenium.

So, for client side, either Chrome or Firefox have great built-in debuggers (filled with watch panes, performance monitors, all the good stuff that you've come to know and love in C++/Java).

As for server-side, if you're using PHP, then I strongly suggest using DBG. If you're not tied to PHP, then I'd also strongly suggest moving to Python and using PDB. PDB, coupled with cProfile just makes development life a lot easier.

If you're accustomed to GDB at all (C++), then both PDB and DBG should be crazy easy to pick up and run with. Both can also be integrated into editors like Eclipse, Netbeans and Vim.


答:
You could always use java or C++ (or ruby, or python, or scala or...) if you really can't stand PHP (which is understandable. A lot of people don't like it.)

If you want to stick with what you're currently using, make sure you're using firebug (though the google chrome dev tools are about to get a lot more awesome) with the FirePHP plugin which will allow you to have a full view of the PHP state and any errors that occur.

Further, make sure you use the PHP Error handling functions in use (but remember to remove them again before you go live, because they're also a great way for malicious users to find out the internals of your app)

As for IDE's, you could always try the Eclipse PHP Developer Tools or use the more dedicated Zend Studio.

Title: How do I make web-application development less frustrating?

Body:
I am fairly new to web-application development.  I just can't shake the feeling that it takes me forever to do anything of even remote complexity.  In c++ and java I could write the same applications in a matter of hours.

On the web debugging is painful (especially if complex json-ajax) is involved.  IDEs suck.  The languages let everything through without errors until it is doesn't work anymore and you are stuck looking for a bug without any error or warning to guide you (and no real good way to step through the program).

Can someone guide me to reading material and/or technologies that would help me find a way to stay sane when developing complex web-applications?

Perhaps the answer is to use a good framework (zend?).  At work we are not really using a framework except for database models generators and basic add/update/delete page generators.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Not really about programming, but...

You can't wait for inspiration. You have to go after it with a club.

  — Jack London

LastEditorDisplayName: Roger Pate


答: I program differently in dynamic languages.  There is no compile-time checking, but neither is there any compile-time delay.  So I write a tiny little bit of code at a time, and then test it.  I start with a blank page, and add one element at a time, testing as I go.  I commit each little change to revision control as soon as it works.  That way if I screw up I can just revert to the previous working state and have another go.  On the server side I have found dynamic languages to be much more productive than Java, because I have to write and read so much less code, and because I never have to mess around with server restarts.</p>


问:
Ruby on Rails downsides and caveats
This is not an opening gambit for RoR bashing - honest!

I'm learning Ruby and the Rails framework. Prima facie it appears to be pretty cool, and a wonderful experience compared to PHP. (In fact, it's reminding me of happier days with C# and .NET.)

However, going into this, I have no experience with this framework or language, and I'm curious - what are the current downsides or things you'd wish you'd known when you were beginning?

(Maybe this should be made a community wiki?)

答:
In my personal experience, the major headache is around compatibility.

When:

there are x rails projects deployed,

each project uses y gems.

while there are n versions of rails,

plus m versions of gems installed,

with several versions of ruby,

on a single Linux box as production machine.

the programmer works on another OS X development notebook.

As a freelancer, who does not have the luxury to update/upgrade most of the things, will face a lot of compatibility issues from above variables... while rails, gems, and ruby keep changing/evolving.

Title: Ruby on Rails downsides and caveats


答:
Using a framework like Ruby on Rails helps ease the frustration a great deal. It has pretty good error reporting, and thanks to ActiveRecord working with models and databases is a snap. As long as you follow the philosophy of convention over configuration, you can prototype complex web applications pretty quickly with RoR.

I'll second Firebug, although the Developer tools for webkit work nicely as well.

Edit for resources:

Here's a great place to get started for free.

www.railstutorial.org


问:
Algorithm design for comparing split times in a race
I need to determine the ranking of values in an array without altering their position, so that I can print the position of each split time next to the actual value of the split time in a table like so.

```<code><table>
<tr>
  <th>Split 1</th>
  <th>Split 2</th>
  <th>Split 3</th>
</tr>
<tr>
  <td>4.66 (1)</td>
  <td>5.12 (3)</td>
  <td>4.75 (2)</td>
</tr>
</table>
</code>```

My array = [4.66, 5.12, 4.75] and I need to iterate through it and print the rank rank as seen in parenthesis above. I can't sort, because I need to do this for several decimals in the html table. Any suggestions for implementing this algorithm?

答:
If you are not sorting the list, you are going to need to iterate over it once (minus 1 element) to determine all of the values rankings.

Or, try maintaining a separate array that sorts on insert, then reference the value (rank) of that key (value or time) when printing your data.


问:
Any suggestions for pair programming with external resource?
I am a software engineer engaged in some extracurricular projects outside of my main gig.  I was considering hiring a developer on Elance to assist me.  Ideally, we would be a collaborative team where I can review their code and our "days" would overlap by a few hours.
Ideally, when that persons day is over, I could do code review and then take off where they left off.

Has anyone attempted this?  Would it be practical to use a Rackspace Cloud Server for this effort where when one developer was done they just saved a VM image that would be accessible by another developer?

Our development environment will be ASP.NET 4.0 MVC 3.

答:
I don't know much about Elance but I work in a company that does distributed development and here are a few things I have learned -

It is very important to have good overlap between your timezones - at least 4 hours is needed in my opinion, since this will allow you to actually collaborate rather than be limited to a short meeting at the beginning or end of your day. Code reviews are a collaborative activity requiring lots of discussion (argument :-) ) in my experience...

You need to have an open channel of communication during the time of overlap while the two of you are working - this can be as simple as an open IRC channel but we use Skype at work and I think the ability to call or video chat on demand make it far superior to IRC. Another option to explore is to use something like a G+ Hangout while you are working - obviously this will mean the both you need to have reliable internet.

Reliable and fast internet is an absolute must and its not that easy - at least where I come from. Ask if the person you are working has a backup power supply and a good internet connection.

At work we use a rackspace server as a development testing server. And we have a CI machine that automatically pulls the source code from GitHub builds and deploys to the server on every commit. I would suggest the same for you guys as well. I think keeping your development environment as a VM in the cloud is not a good idea, especially since you guys are presumably planning to use a MS Windows machine to remote into. That can get quite laggy and development experience is not very good. Having a machine to deploy your code on also forces you to test it in the right environment (a limited permission server machine with locked down IIS) and also build deployment into your design and development schedule.

I am assuming you can leverage eLance for your project management needs but a good online project management tool is a must to ensure you are heading in the right direction :-)

I hope this answer helps - on reading your question I realize that only point 4 covers the actual question you asked but I have decided to leave the rest in as well in the hope it helps others thinking of collaborative development as well...


答:
I'd do something like this:

Create a data structure containing a time value and an integer value.

Iterate over your original array, and create a second array of the data structures.  The second (integer) value would be the index of each time in the original array.

Sort the second array by time.

The position of each time in the sorted array is the rank.  You can apply ranks back to the original array by using the index value.

Title: Algorithm design for comparing split times in a race

Body:
I need to determine the ranking of values in an array without altering their position, so that I can print the position of each split time next to the actual value of the split time in a table like so.

```<code><table>
<tr>
  <th>Split 1</th>
  <th>Split 2</th>
  <th>Split 3</th>
</tr>
<tr>
  <td>4.66 (1)</td>
  <td>5.12 (3)</td>
  <td>4.75 (2)</td>
</tr>
</table>
</code>```

My array = [4.66, 5.12, 4.75] and I need to iterate through it and print the rank rank as seen in parenthesis above. I can't sort, because I need to do this for several decimals in the html table. Any suggestions for implementing this algorithm?


问:
What are the reasons that make PHP more popular for freelancing world?
In many freelancing websites, you see many job ads for PHP (backed by MySQL). However, job ads for .NET, Java, Ruby, etc. are not that much. What are the reasons which make PHP so popular for freelancing? Is it because of its importance? Or is it because PHP is free?

The reason I'm asking this question is that, I'm an ASP.NET developer and while I see that ASP.NET development productivity is higher (because of fascinating tools it has), it still doesn't attract developers as much as PHP. I want to know if I'm missing something here that I should take into account or no.

答: ASP.NET runs on Microsoft servers. So, in order to have ASP.NET running, the company must have obtained the appropriate licenses. If a company has the money to purchase licenses - these aren't cheap either - then it's very likely they have the money to pay for an in-house development team.</p>


答:
Use quicksort (or the sorting algorithm of your choice) to sort a list of array indexes according to the corresponding split times. The array of indexes is a proxy for the array of split times. We don't want to change the order of the times, but we want to know what the order of the times would be if we sorted it.

Given split time array: splits[] = {4.2, 3.9, 4.1, 3.8, 3.7}

We start with an array of indices: indexes[] = {0, 1, 2, 3, 4}

Now we sort indexes array using the values from splits. Any sorting algorithm needs a comparison function, and ours is:

```<code>compare(i, j) := if splits[i] < splits[j], i is smaller,
                 else if splits[i] > splits[j], i is larger,
                 else they're equal
</code>```

So, for example, compare(0, 1) should return i > j because 4.2 > 3.9.

Following is some C code that illustrates the solution using fairly little code. It relies on the qsort_r() C standard library function, which is a version of quicksort, but you could use any sorting algorithm. An important implementation detail is that the qsort_r() routine lets us pass an extra parameter that's provided to the comparison function; this lets us pass the splits array to the comparison function.

```<code>void sortSplits(float splits[], int index[], int count)
{
    // initialize the index array
    for (int i = 0; i < count; i++) {
        index[i] = i;
    }

    qsort_r(index, count, sizeof(int), splits, compareSplits);
}

int compareSplits(void *thunk, const void *item1, const void *item2)
{
    float *splits = (float*)thunk;
    int i = *(int*)item1;
    int j = *(int*)item2;

    if (splits[i] < splits[j])
        return -1; // less than
    else if (splits[i] > splits[j])
        return 1;  // greater than
    else
        return 0;  // equal
}
</code>```

To use this code, call sortSplits() passing in the array of split times, an array of ints that's at least as long as the array of times, and the number of times. On return, the index array will contain the sorted list of indexes. In other words, if the resulting array looks like:

```<code>{3, 0, 1, 2}
</code>```

it means that the split time at index 3 is the smallest, followed by the time at index 0, followed by the time at index 1, followed by the time at index 2.

The indexes here really work like pointers. You could even say that they ARE pointers in a sense. Indeed, you could implement exactly the same algorithm described above using an array of pointers in place of the array of indexes That would eliminate the need for passing the splits array as a separate parameter.

Body:
Use quicksort (or the sorting algorithm of your choice) to sort a list of array indexes according to the corresponding split times. The array of indexes is a proxy for the array of split times. We don't want to change the order of the times, but we want to know what the order of the times would be if we sorted it.

Given split time array: splits[] = {4.2, 3.9, 4.1, 3.8, 3.7}

We start with an array of indices: indexes[] = {0, 1, 2, 3, 4}

Now we sort indexes array using the values from splits. Any sorting algorithm needs a comparison function, and ours is:

compare(i, j) := if splits[i] < splits[j], i is smaller,
                 else if splits[i] > splits[j], i is larger,
                 else they're equal

So, for example, compare(0, 1) should return i > j because 4.2 > 3.9.

Following is some C code that illustrates the solution using fairly little code. It relies on the qsort_r() C standard library function, which is a version of quicksort, but you could use any sorting algorithm. An important implementation detail is that the qsort_r() routine lets us pass an extra parameter that's provided to the comparison function; this lets us pass the splits array to the comparison function.

void sortSplits(float splits[], int index[], int count)
{
    // initialize the index array
    for (int i = 0; i < count; i++) {
        index[i] = i;
    }

    qsort_r(index, count, sizeof(int), splits, compareSplits);
}

int compareSplits(void *thunk, const void *item1, const void *item2)
{
    float *splits = (float*)thunk;
    int i = *(int*)item1;
    int j = *(int*)item2;

    if (splits[i] < splits[j])
        return -1; // less than
    else if (splits[i] > splits[j])
        return 1;  // greater than
    else
        return 0;  // equal
}

To use this code, call sortSplits() passing in the array of split times, an array of ints that's at least as long as the array of times, and the number of times. On return, the index array will contain the sorted list of indexes. In other words, if the resulting array looks like:

{3, 0, 1, 2}

it means that the split time at index 3 is the smallest, followed by the time at index 0, followed by the time at index 1, followed by the time at index 2.

The indexes here really work like pointers. You could even say that they ARE pointers in a sense. Indeed, you could implement exactly the same algorithm described above using an array of pointers in place of the array of indexes That would eliminate the need for passing the splits array as a separate parameter.


答:
To determine the ranking you'll need to sort the array in a temporary sorted array. Easiest way I can think of is to create a data structure that contains both the time and the ranking, e.g. Javascript style:

```<code>var data = {
    time: 4.66,
    rank: 1
}
</code>```

So first start building up your list with the raw data converted to rankable data objects:

```<code>var times = [];
var tempTimes = [];
var i;
// create from input arr objects and put to times and tempTimes
for (i = 0; i < arr.length(); ++i) {
    var obj = {
      time: arr[i]
    };
    times[i] = obj;
    tempTimes[i] = obj;
}

// sort tempTimes by time, using jQuery
tempTimes.sortElements(function(a, b) {
    return a.time > b.time ? 1 : -1;
});
// iterate and add ranks to the objects
// since they are now ordered by time
for (i = 0; i < tempTimes.length(); i++ ) {
    tempTimes[i].rank = i;
}

// since times and tempTimes have the same objects
// (by reference), they should all now be updated
// with the ranks set so use the times array to print
// out the array with the ranks, since that is still
// in correct original order
printTable(times);
</code>```

This would be done a bit differently in other languages, by exploiting their idioms, but the basic step of creating a data structure that contains both time and rank still remains throughout all. The basic data flow would look like the following diagram:

```<code>list of raw data
   |
   | convert
   v
list of rankable data ---wait for ranks to be set---> output
   |                        ^
   | sort by times          |
   v                        |
list of rankable data       |
sorted by time              |
   |                        |
   | add rank to data       |
   v                        |
list of data ranked --------+
by time
</code>```

Body:
To determine the ranking you'll need to sort the array in a temporary sorted array. Easiest way I can think of is to create a data structure that contains both the time and the ranking, e.g. Javascript style:

var data = {
    time: 4.66,
    rank: 1
}

So first start building up your list with the raw data converted to rankable data objects:

var times = [];
var tempTimes = [];
var i;
// create from input arr objects and put to times and tempTimes
for (i = 0; i < arr.length(); ++i) {
    var obj = {
      time: arr[i]
    };
    times[i] = obj;
    tempTimes[i] = obj;
}

// sort tempTimes by time, using jQuery
tempTimes.sortElements(function(a, b) {
    return a.time > b.time ? 1 : -1;
});
// iterate and add ranks to the objects
// since they are now ordered by time
for (i = 0; i < tempTimes.length(); i++ ) {
    tempTimes[i].rank = i;
}

// since times and tempTimes have the same objects
// (by reference), they should all now be updated
// with the ranks set so use the times array to print
// out the array with the ranks, since that is still
// in correct original order
printTable(times);

This would be done a bit differently in other languages, by exploiting their idioms, but the basic step of creating a data structure that contains both time and rank still remains throughout all. The basic data flow would look like the following diagram:

list of raw data
   |
   | convert
   v
list of rankable data ---wait for ranks to be set---> output
   |                        ^
   | sort by times          |
   v                        |
list of rankable data       |
sorted by time              |
   |                        |
   | add rank to data       |
   v                        |
list of data ranked --------+
by time


答: One reason - cheap and ubiquitous hosting.</p>

Title: What are the reasons that make PHP more popular for freelancing world?

Body:
In many freelancing websites, you see many job ads for PHP (backed by MySQL). However, job ads for .NET, Java, Ruby, etc. are not that much. What are the reasons which make PHP so popular for freelancing? Is it because of its importance? Or is it because PHP is free?

The reason I'm asking this question is that, I'm an ASP.NET developer and while I see that ASP.NET development productivity is higher (because of fascinating tools it has), it still doesn't attract developers as much as PHP. I want to know if I'm missing something here that I should take into account or no.


问:
Multiple Joins or Simple Readable Database Calls
Curious how other developers feel about this. I come across some pretty nasty sql joins, as we all do I'm sure. I would prefer making more database calls for the sake of readability and simplicity rather than have a large SQL statement to maintain; about 3 - 4 joins. For the performance argument, I will give up a little performance for readability.

For example: make the first call, filter the data, and then query the second table, and so on

What is your preference?

答:
I often see facepalm-worthy code that fetches a result set and loops over it, executing another SQL query against a referenced table for each row.  Why?  "Because joins are bad."

For example (pseudocode):

```<code>SELECT * FROM Users;
for each user row {
    SELECT * FROM Orders WHERE Orders.user = $user;
    for each order row {
         SELECT * FROM LineItems WHERE LineItems.order = $order;
         for each lineitem row {
             SELECT * FROM Products WHERE Products.id = $lineitem;
         }
    }
}
</code>```

If you design tables and indexes well, joins are an efficient way of filtering data within the RDBMS, and returning a small result set.  Certainly more efficient than doing the equivalent work in application code.

OwnerDisplayName: Scott Radcliff

Body:
I often see facepalm-worthy code that fetches a result set and loops over it, executing another SQL query against a referenced table for each row.  Why?  "Because joins are bad."

For example (pseudocode):

SELECT * FROM Users;
for each user row {
    SELECT * FROM Orders WHERE Orders.user = $user;
    for each order row {
         SELECT * FROM LineItems WHERE LineItems.order = $order;
         for each lineitem row {
             SELECT * FROM Products WHERE Products.id = $lineitem;
         }
    }
}

If you design tables and indexes well, joins are an efficient way of filtering data within the RDBMS, and returning a small result set.  Certainly more efficient than doing the equivalent work in application code.

OwnerDisplayName: Bill Karwin


答:
In my experience, larger queries give SQL Server more opportunities to get it wrong.  Using smaller queries can help SQL Server use a good query plan.  For example, in your development environment, SQL Server might perform a huge query exactly in the order you wrote it.  Later, when the code migrates to production, suddenly the data is much different.  SQL Server might make a wrong assumption and choose to start the query in the middle, and suddenly you end up with crazy joins that create a billion temporary records that get spooled to tempdb.

Performance of complicated queries against huge databases varies.  Sometimes, having a complicated query performs better, because it processes the data only once.  Sometimes, separating steps is both faster and more readable, because you can ensure the results of the first query limit the data to a small set of rows before performing the rest of the steps.

I try to use separate queries for separate logical steps.  I'll document each step with comments so I can more easily remember what it was trying to accomplish.  For example:

Do some pre-processing to figure out what the user wants

Gather the data, filtering to the user's selection

Fill in some date-based data from some pricing table

Drop a few records that are not relevant because of some rare condition

Fill in some fields for reporting purposes

Return the results

If you are joining to multiple levels of sub-queries, as in Bill's example, then breaking apart the sub-queries into separate steps can improve performance.

Also note that your plan may incur more I/O as you create, populate, index, and select from temporary tables.

And finally, if it ain't broke-- don't fix it!

Title: Multiple Joins or Simple Readable Database Calls

Body:
Curious how other developers feel about this. I come across some pretty nasty sql joins, as we all do I'm sure. I would prefer making more database calls for the sake of readability and simplicity rather than have a large SQL statement to maintain; about 3 - 4 joins. For the performance argument, I will give up a little performance for readability.

For example: make the first call, filter the data, and then query the second table, and so on

What is your preference?

OwnerDisplayName: Paul Williams


答:
You are thinking of this from the wrong side. I quote:

I see that ASP.NET development productivity is higher [...], it still doesn't attract developers as much as PHP.

But you're looking at job ads. Job ads are not written by passionate developers, but by the business people who wants things to be done at the lower cost, no matter if the language sucks as PHP.

From their position (imagine it's written in bold Arial Black 200), PHP has strong benefits over ASP.NET:

ASP.NET is Microsoft. Microsoft is evil. So ASP.NET is evil. It may not be true in some countries, especially United States. It is very true on the other hand in others. In France, small or medium size companies have a very poor opinion of Microsoft, and mostly large companies use ASP.NET, sometimes for legacy purposes.

ASP.NET is a proprietary product. You do not want to depend on a product of a precise company. Here's the problem. Microsoft had ASP. It sucked, but it was used by companies. Then Microsoft released ASP.NET, and ASP become obsolete. Today, Microsoft releases ASP.NET MVC. What will happen to ASP.NET, considered by many people as too ugly compared to ASP.NET MVC?

ASP.NET can be run on Windows and... well, that's all. PHP can be run everywhere, especially on both Windows and Linux. Linux is free. Windows Server cost is so high than no many small companies can afford it on their server. I don't even mention the price of the optional Microsoft SQL Server.

ASP.NET cannot be used on Apache, while Apache is the most used server and most system administrators know how to administer it. Of course, there is Mono, but it's more a solution for geeks, not for a person who runs a business.

ASP.NET hosting is slightly more expensive, due to the cost of Windows Server. But maybe it's just an impression.

ASP.NET developers are not too many, while there are plenty of inexperienced PHP programmers ready to work for food. If you don't need a high quality website, the cost may be reduced even more.

ASP.NET is compiled. If you forget to say in your contract that the developer must provide you the source code, you may find yourself with the binaries only. What if you want to search for another developer to modify the project later? In PHP, source code may be obfuscated, but it's not the usual practice.

ASP.NET is not widely used. Even in reality it is, the business people don't see it too much (again, it must be false in USA, but is certainly true in France and probably other countries in the same situation). One of the most known websites using ASP.NET MVC is Stack Exchange. But have you seen a business person who knows what it is? It's very easy to convince a person to use PHP. "Look, Facebook uses PHP. Wikipedia uses PHP. How can it be bad?" Business people like those simple arguments, and remember them much better than "Do you know that actually Facebook developers themselves said that PHP suck because of its poor performance?".

Additionally to those points, business people often have strange reasons to choose PHP. For example I often hear them saying that "PHP is more secure" or "PHP is faster than ASP.NET because it's not compiled¹". I never succeeded to make them explain why is it so and where have they heard this stupidities.

¹ Actually this one comes from a few websites or forums comparing PHP with ASP.NET and written by less than competent people. I quote the first link, because at this level, it's just... astonishing: "ASP.net is compiled into memory in binary code. So, when ASP.net is used for coding, it is evident that it takes much longer time to process since the codes need to be retrieved from memory. However, PHP is not compiled into memory like ASP.net is. It is interpreted at runtime. That is the reason why PHP coding leads to better speed and even efficiency.".


问:
Where to look for challenging jobs with a relaxed atmosphere?
I'm a dev at one of the big-name tech companies. I like the job for many reasons:

I do interesting work on a cool product

I solve challenging problems and use a lot of high-level skills (quantitative, creative, writing, presenting)

It pays well

The problem is that I feel I need a more relaxed atmosphere (shorter hours, less performance pressure, and more flexibility), in order to free up time for other pursuits and reduce stress. The ideal would be a job that's around 30-35 hours a week, where there is flexibility to work more or less in a given week. Can anyone suggest where to look for a job like this, where I wouldn't have to sacrifice too much on the above points? (Obviously I would have to sacrifice pay.) My employer does not generally offer part-time employment.

The closest thing I can think of is when I did summer internships at my university's CS department. The work was very intellectually challenging, but if I needed to go home a couple hours early or get flexibility on a due date, nobody batted an eyelash. However, I'd like to find out if there are alternatives to academia since from what I've seen the pay there is a gigantic drop from what I'm currently making.

I've done freelance development before, but I do like that as an employee of a large company I have a lot of things taken care of for me (e.g. benefits and guaranteed stable employment).

答:
Your friends and family will be the best bet here - unless you have a first-hand account of the working environment, it's basically impossible to see what you're getting into when you turn up for a job interview.

Anything less than 36 hours a week is part-time employment, so it'll be hard matching that kind criterion right off the bat. Keep talking to people and soon enough, you'll find a work environment that matches your desires.

Keep in mind that no company is going to dish out money for people bludging around. People want to be surrounded by others who are smart and get things done.

Disclaimer: I have a job (salary) that I find extremely interesting. I choose when to get to work, when to leave work and when to work from home. I get treated as an adult, so I'm prone to be bias in my answer.


答:
From my point of view, there is a simple reason for a freelancer to choose PHP over ASP.NET: it's free, and as a freelancer, I do not have to pay anything to develop a website for a customer. That is a big deal, especially for my customers.

This basically says that I will spend less money and get more happy customers. Remember, customers that normally seek freelancers don't really want something big and highly sophisticated which also adds another point to why they'd like to spend less money and thus says why I should develop their websites in PHP rather than anything else.


问:
What determines when a computer is considered a "client"?
In web development the terms "server" and "client" are often refered to when discussing how pages are requested on the web. It is also used exstensively when talking about PC, phone, tablets, etc. The question that came to my mind was what qualified a computer to be considered a client?

I took a look at this article from wikipedia and noticed that clients are considered service requesters whereas Servers are considered service providers. If this is true couldn't all computers that request a service in a sense be considered a client?

The stereotype I noticed is that a client computer is usually synonymous with a "consumer" computer, but according to wikipedia this is not entirely accurate. Any idea on how to draw the line in this common scenario?

答:
A server provides a specific set of services and client(s) use that service.

The simplistic answer is that the client initialises the connection or sends the first UDP packet, the server accepts the connection.  This is because the server is happy to run even if it has nothing to do, waiting for the client to tell it what to do.  The client needs a server to get it to do things for it. A server often serves many clients and often does something specialised.  The client usually is an aggregate of services and delegates wok to servers.

The one which is often confusing is X-Windows is the server the your desktop and the client is an application on a remote machine.  This is because the server is the one which displays the application and interacts with the user on one or more applications behalf. The client application makes requests to the server to draw this or that and gets feedback or results from the server.


问:
Choosing the type of Index Variables
We use Integer type represent index variables most of the time. But in some situations, we're forced to choose

```<code>std::vector<int> vec;
....

for(int i = 0; i < vec.size(); ++i)
....
</code>```

This will cause the compiler to raise the warning that mixed use of signed/unsigned variables. if I make the index variable as for( size_t i = 0; i < vec.size(); i++ ), (or an unsigned int )it will sort out the issues.

When it come more specific to use windows types, most of the Windows APIs are dealing with DWORD (which typedef-ed as unsigned long).

So when I use similar iteration, will again cause the same warning. Now if I rewrite it as

```<code>DWORD dwCount;
....

for(DWORD i = 0; i < dwCount; ++i)
....
</code>```

I find this a bit weird. It might be the problem withe perceptions.

I agree that we are supposed to use the same type of index variable to avoid the range problems can happen with the index variables. For e.g if we're using

```<code>_int64 i64Count; //
....

for(_int64 i = 0; i < i64Count; ++i)
....
</code>```

But in the case of DWORD, or unsigned integers, are there any problems in rewriting it as

```<code>for(int i = 0; (size_t)i < vec.size(); ++i)
</code>```

How most of the people are working with similar issues?

答:
```<code>std::vector<int> vec;

for(int i = 0; i < vec.size(); ++i)
</code>```

Use an iterator for this, not a for loop.

For the others, as long as the variable type is of the same size, static_cast should work just fine (i.e. DWORD to int16_t)

Title: Choosing the type of Index Variables

Body:
std::vector<int> vec;

for(int i = 0; i < vec.size(); ++i)

Use an iterator for this, not a for loop.

For the others, as long as the variable type is of the same size, static_cast should work just fine (i.e. DWORD to int16_t)


答:
The kind of job you are looking for doesn't automatically exist in North America, in the software field. It's so exceedingly rare (assuming you're not willing to give up work quality, too), that your chances for finding it pre-defined are best for just stumbling into it by random chance.

Your best bet is to invent the job yourself. The two standard alternatives are to build up a contracting type portfolio and lifestyle, or going into business for yourself.

The third, less often mentioned alternative, is to pick a subset of what you are good at and specialize at it until you are good to be clearly within the 0.05% on your market. In the US, that means you'll be one of the top 500-600 developers in the country. Once you're recognizably that good, you can dictate the terms of your own employment, including the number of hours worked and exposure to stress, etc...

Title: Where to look for challenging jobs with a relaxed atmosphere?

Body:
I'm a dev at one of the big-name tech companies. I like the job for many reasons:

I do interesting work on a cool product

I solve challenging problems and use a lot of high-level skills (quantitative, creative, writing, presenting)

It pays well

The problem is that I feel I need a more relaxed atmosphere (shorter hours, less performance pressure, and more flexibility), in order to free up time for other pursuits and reduce stress. The ideal would be a job that's around 30-35 hours a week, where there is flexibility to work more or less in a given week. Can anyone suggest where to look for a job like this, where I wouldn't have to sacrifice too much on the above points? (Obviously I would have to sacrifice pay.) My employer does not generally offer part-time employment.

The closest thing I can think of is when I did summer internships at my university's CS department. The work was very intellectually challenging, but if I needed to go home a couple hours early or get flexibility on a due date, nobody batted an eyelash. However, I'd like to find out if there are alternatives to academia since from what I've seen the pay there is a gigantic drop from what I'm currently making.

I've done freelance development before, but I do like that as an employee of a large company I have a lot of things taken care of for me (e.g. benefits and guaranteed stable employment).


答:
PHP is still to my knowledge the only language that provides straight forward, no-frills application development and deployment.

Other interpreted languages such as Python and Ruby are slower when hosted in basic CGI modes, not conducive for cheap or free hosting.  Perl is well known for its learning curve but more importantly its error handling is adverse to hacker web development methodology.

Everything else requires a setup process, Django, Ruby-on-Rails, Java, which acts as a huge barrier to stop people playing with web technologies.


答:
Some tools that I use to improve my development are:

Visual Web Developer 2010 (part of Visual Studio 2010)

You said IDE sucks. With this you now have one of the best IDE out there, and if you used to code in C++ I bet you already know VS. I use the express version which is free and I don't need more.

JS Fiddle and Codepad

Great to try out HTML/CSS layouts, and JS scripts. Codepad is great to tryout your website in server-side languages.

Firefox + Firebug (or other browsers equivalents)

Debugging scripts is far easier using the browsers. You also have a complete tree-style DOM you can manipulate as you wish and changes will be applied in real time.

Use a framework

There are various frameworks for every web language out there. They offers you a set of functionalities well tested that ensures cross-browser compatibility, save you a lot of time of debugging, and "write less do more". I suggest looking into jQuery and YUI for JavaScript coding.

Console Log

To track your debugging progress, use a Debug Console, integrated in most browsers. In JS, using console.log('something to write'); will add a text entry to the debug console, this way you can add useful information to your code for debugging purposes and keep track of your code execution.

Boilerplate

Now don't get me wrong. I know you are into web application development and not normal website. But the fact is, it's still a website, and you still need to take care of the most important issue you have: cross-browser compatibility. This is a solid template which will give you a solid base for your HTML pages, and much much more...

CSS Reset

If you're not using Boilerplate, which comes with his own CSS reset, you may still want to make sure your pages looks correctly among browsers. A CSS Reset will ensure this. My favorite is YUI CSS Reset, together with CSS Base and CSS Fonts.


答:
Target small businessess.  They are the most flexible with hours.  A smaller company may more than welcome the opportunity to have access to an experienced developer for a lower cost (paying for fewer hours/wk).  How do I know?  I've done exactly this a number of times.

The trick is... you gotta ask.  You might be suprised at the response. I've known folks who have done this with larger companies too.  Of course, not everyone will go for such an arrangement - but do you really want to work for such conventional thinkers?

The downside - dont expect all the perks of full time employment.  Depending on where you are, that may mean having to purchase your own insurance, handle your own retirement funds, etc.


答:
The difficulty of a bug can be
  measured as the distance, in lines of
  code, from the cause of a bug to the
  visible symptom of a bug.

The Klophaus Equation of Bug Difficulty

Body:
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

OwnerDisplayName: Russell


答:
I'm doing 30hrs/week jobs for more than a decade now. In my experience you will not find a niche in the industry where part-time jobs are waiting for you to grab one. Instead, you will have to carve such a job out of the common job market. That's not easy, because many only bargain for money when they interview, so companies are not used to employers wanting to work less, but it's not impossible.

I have found the following important when looking for a part-time job:

Be good at what you do. When you are good, they will want you, and are prepared to pay for it. Some candidates will want more money, some will want more holidays, a few will want fewer working hours.

In an interview, explicitly ask about a company's overtime policy. Is overtime something normal at the shop, that's done by everyone regularly? Unpaid? If so, you will be unlikely to really be working less than 40hrs, no matter what contract you sign.

If you have the feeling they might be hard to convince to let you work 30hrs, start out offering less (20hrs?) and then let yourself be "persuaded" to work 30hrs. :) I did this with my first part-time job.

Don't expect too much pay or other benefits when you first do this. Under these conditions you are closer to a junior job than you used to be. Once you can show excellent references for two or three such jobs over the last decade it will be easier to convince employers that your special needs are worth the hassle.

Once you have such a job, be sure to follow these rules:

I usually explain upfront, right in the interview, that I am never working for free. I clock every hour I work for the company, and certainly clock overtimes I put in, and I expect to take leave the same amount of hours for compensation. (I have, twice over more than a decade, accepted money instead. But that was me accepting it, rather than them pressing me to do it.)

Do not let them press you into doing more hours without compensation. You might have relinquished other benefits (like money) for doing 30hrs/week. There is no point in relinquishing what you got for that. (The others wouldn't give up that money even if pressed hard, right?)

Remind everyone that you only have 75% of the time others have. Make sure that your team leader, when planning resources, remembers that. If they have never worked with such an employee, then this will need constant reminding in the beginning.

We all know that in this industry crunch time is a common phenomena. When others work overtime, you might have to do that, too. However, be sure to make it absolutely clear that for you, 40hrs/week already is overtime.

ContentLicense: CC BY-SA 4.0


答:
XDebug could help you debug in a fashioncloser to what you're used to with VS (the latest versions of Wampserver  ship with Xdebug (both server and client), if you're looking for an easy development install that installs everything you need except a text editor).

Also, if PHP isn't your thing, try another language: you may be happier with Python, Ruby/Rails, ASP or Perl.

Also, you could write C++ CGI modules instead of PHP scripts, though I would advise to try PHP some more, it's quite handy once you get the hang of it.


问:
When developing algorithms, is skipping the pen&paper phase a bad habit?
I heard many people saying that when developing algorithms you should first use pen and paper, flowcharts and what not, so that you can focus on the algorithm itself, not worrying about the implementation of said algorithm (i.e., you deal with one problem at a time).

However, most of the time I find it easier to actually develop my algorithm on the fly. That is, I think a bit about the problem until I know the general direction to take, and then I start writing code and making changes until the algorithm emerges and works.

Is this a bad habit that I should try to change?

答:
Who are these "many people?"  And are they programming for a living?  What you are doing is exactly what most programmers do, at least most that I have known.  There's little use for paper when it's faster to type, and little use for pseudo-code when programming in a high-level language.  Occasionally I do use pen and paper to visualize a tricky algorithm (e.g. rotating a tree), but mostly I start with high-level code and gradually fill in the blanks.

Like KLE, I think this works better following test-driven development.  Assuming you are going to write tests anyway, you may as well write them first.


问:
Infinite Bitmap
I'd like to build a bitmap during runtime. The bitmap should be scalable on all sides and pixel access should be quiet efficient.

Some illustration http://img546.imageshack.us/img546/4995/maptm.jpg

Between and after the commands shown in the picture, Map.setPixel() and Map.getPixel() should set/return data saved in the bitmap.

I don't expect an implementation just a concept how to allocate memory in such a way that the setPixel()/getPixel is as fast as possible.

答: @SecStone said that there's enough time available for the expansion operation, so the easiest and most efficient way to store the pixels is using a single flat array or a two dimensional array, as pixels can be accessed in constant time then.</p>

Title: Infinite Bitmap


答:
The most flexible and perhaps reliable implementation is a linked list with structs giving x-coordinate, y-coordinate, and bit value. I would build that first and get it working.

Then, if it is too slow and/or big, try the usual ways of speeding it up: array, matrix, bitmap, compression, caching, inversion, storing only '1' values, etc.

It is easier to make a slow correct implementaiton faster than it is to fix a buggy fast implementation. And while testing your 'fast' second implementation you've got a refernce standard to compare it against.

And, who knows, you'll probaby discover that the slow version is fast enough. As long as the entire structure fits in memory, things are amazingly fast already.

Title: Infinite Bitmap

Body:
I'd like to build a bitmap during runtime. The bitmap should be scalable on all sides and pixel access should be quiet efficient.

Some illustration http://img546.imageshack.us/img546/4995/maptm.jpg

Between and after the commands shown in the picture, Map.setPixel() and Map.getPixel() should set/return data saved in the bitmap.

I don't expect an implementation just a concept how to allocate memory in such a way that the setPixel()/getPixel is as fast as possible.


问:
Identify Service Oriented Architecture
How can I tell if a system is built upon a service oriented architecture when reading its source code?</p>

答:
Normally, unless you are the person responsible for it you are not required to know it. You may not see anything in the "code" but rather in configuration files. If you spot configuration files on how to communicate with remote services, for example with an ESB, or as @keppla said via RPC, SOAP, then there are chances that some form of SOA-architecture is used - at least - between these two components.

But if you really want to know though, you may ask the architect, or the IT manager, they should know.

Title: Identify Service Oriented Architecture


答:
Imho the best BASIC to use for upgrading from GWBASIC is PowerBasic (www.powerbasic.com). Many have done this before, so there's quite a lot of experience in Powerbasic's user community should you need assistance there.

Also Powerbasic is a high quality product with almost no problems/bugs and actively developed. It's not free ($199) but worth every penny.

FYI: I'm not affiliated with them and use VB.NET myself (for professional reasons; otherwise it would be Powerbasic ...).

Title: How mature is FreeBASIC?

Body: A friend of mine is considering using FreeBASIC in a critical production environment. They currently use GWBasic, and they want to make a soft transition towards more modern languages. I am just worried that there might be undetected bugs in the software. I see that their version number is 0.22.0, which indicates, that it is not quite mature yet. I also read this discussion, without being able to conclude. Also on their Sourceforge pages there is no indication of whether it is Alpha or Beta (which anyways is not a very good indicator). Does anyone have own experience about the maturity, ideas on how to judge the maturity, or know of companies using FreeBASIC in a critical production environment?</p>


答:
If the extend() operation needs to be reasonably fast, a Quadtree might be a good fit; it actually wouldn't even require explicit extend operations. Admittedly, it would not yield optimal performance for random access to individual pixels, but your comment says that your primary operation is iterating over the pixels, which a quadtree could do very fast, perhaps almost as fast as a matrix-based implementation (and faster if iteration does not always happen in the same way the matrix is laid out).

Your requirements actually sound like you're trying to implement a cellular automaton like the Game of Life. You might want to take a look at Hashlife, an extremely high-performing way to implement the Game of Life on an infinite grid. Note that it's based on a Quadtree, but does some very smart additional optimizations based on the locality of the game rules.

Title: Infinite Bitmap


问:
Real-time chat in Ruby on Rails without owning a server
I'd want to implement a Real-time chat for my Rails app but I can't really host the server which handles the sockets. I've tried Faye but it needs a server. I've also heard of pusher but it's limited to 20 users at a time on the chat and I can't really be sure they won't be more.

I've thought of IRC but I think I can't really embed it into a rails app, maybe it needs sockets...

How can I implement a real-time chat without owning a server?

答:
If you want to try something new, you can use :

html5 websocket

node.js or

em-websocket or

cramp

For you, cramp might be useful. I have created a basic demo for a peer to peer chat. It is not for production, but you can find out enough information :

em-wesocket Chat Demo

It is done with em-websocket and socket.io.

In this demo, I am not using redis but with redis you can achieve more scalability and persistence.

Cramp or nodejs will work for you.


答:
I'd recommend sketching the general directions (the "pen & paper" phase) before jumping to implementation to save time by getting the most obvious requirements/constraints out of the way.

Then you can finetune it on the way given you can never guess everything at the start because further contraints may/will appear later in development, for various reasons.

That way you know where you're going but you can still adapt to changes.

Title: When developing algorithms, is skipping the pen&paper phase a bad habit?

Body:
I heard many people saying that when developing algorithms you should first use pen and paper, flowcharts and what not, so that you can focus on the algorithm itself, not worrying about the implementation of said algorithm (i.e., you deal with one problem at a time).

However, most of the time I find it easier to actually develop my algorithm on the fly. That is, I think a bit about the problem until I know the general direction to take, and then I start writing code and making changes until the algorithm emerges and works.

Is this a bad habit that I should try to change?


问:
Determine Better Coding Practice
As a new programmer, it has always been hard to create applications, because I am still at the learning stage.

I understand that to achieve a particular affect or function in an application, there will be numerous ways to achieve the same result.

However, should I just purely create a function to it's working state, which means that as long as it works, just as the way I want it to, then it should be fine.

Can any fellow programmers of a higher level kindly let me know the right way of doing things?

答:
We are all still at the learning stage. It will last forever.

I think the best way to improve your knowledge is by learning from other's code or by doing pair programming with higher profiles than you.

Therefore, you should do the following:

Ask for pair reviewing or programming actively. Don't wait for this to be proposed to you. If you are a solo developer, consider online reviewing platforms.

Read as much code as you can. It's how I learn many of the feature of the .NET framework. "Oh I wasn't aware I could do that in just one line of code!". It's like novel writers that gets their ideas from others authors. Don't know where to look? Pick a random open source project and browse in it, just like Stanley Kubrick did to get his inspiration: going to library and picking ANY book in ANY category.

In one Kubrick’s biographies he is described as using a simple method to expand his knowledge base. He would visit his library and select random books from random information categories, without even looking at the titles. He would then force himself to read those books. By doing this Stanley was forcing his mind to expand into new territory on a regular basis.

In order to learn even more quickly, put what you see in practice, in your own code or in samples projects. It will help a lot to memorize.

Learning is probably what drives us all in programming. It's a perpetual exploration.

Title: Determine Better Coding Practice


问:
Why is JavaScript not used for classical application development (compiled software)?
During my years of web development with JavaScript, I come to the conclusion that it's an incredible powerful language, and you can do amazing things with it.

It offers a rich set of features, like:

Dynamic typing

First-class functions

Nested functions

Closures

Functions as methods

Functions as Object constructors

Prototype-based

Objects-based (almost everything is an object)

Regex

Array and Object literals

It seems to me that almost everything can be achieved with this kind of language, you can also emulate OO programming, since it provides great freedom and many different coding styles.

With more software-oriented custom functionalities (I/O, FileSystem, Input devices, etc.) I think it will be great to develop applications with.

Though, as far as I know, it's only used in web development or in existing softwares as a scripting language only.

Only recently, maybe thanks to the V8 Engine, it's been used more for other kind of tasks (see node.js for example).

Why until now it's only be relegated only to web development? What is keeping it away from software development?

答:
Recently node.js has brought server-side development forward. So, it's now possible to write JavaScript, for development.

That's true. In history, it hasn't been used as a development language. But, hey, even scripting in client environment (User Agents) is a type of development. Isn't it?

The main reason that I've heard and read in many weblogs, is that, people didn't know about its power and uniqueness till recent years. What made this happen, was maybe that other languages were doing their job just well enough, and nobody ever thought about making something parallel.


答:
If it's just 3-4 simple joins, I probably wouldn't fret it too much; that isn't much at all in any reasonably large database. I've seen SQL queries that approach that number of dozens of joins, with subjoins to subjoins - now that is when it starts getting unwieldy! Usually there is a good reason for almost each and every one of them when taken in isolation, but at some point it went from being reasonable to unreasonable to sheer madness with "just one more" condition or field needed. At some point you need to consider refactoring the query (when you find that in order to achieve reasonable performance, the join ordering becomes significant or query hints are needed, that's usually a big warning sign), and breaking it into multiple smaller queries, but unless those joins are truly horrendous, I don't think you are at that point just yet.

The single most important rule though is to actually try it. Look at the execution plan. Is the database server making the most efficient use possible of indexes, or can you perhaps add a filtered index on some table that will help performance without hurting too much in other places? Rewrite the query and compare the execution time, I/O requirement and execution plan. Does it actually help? Also do keep in mind that in any non-trivial query, by rewriting it (even if it seems "simple"), you run the risk of introducing a bug.


答:
My favourites have already been posted, so here's something I thought of one day at work:

In Soviet Russia, exception throws YOU!!

Title: What's your favourite quote about programming?


答:
By Hand

If memory is not a very sparse resource, I consider working in bigger chunks.

Here's some pseudo-code.

```<code>class Chunk {
    Chunk new(int size) {...}
    void setPixel(int x, int y, int value) {...}
    int getPixel(int x, int y) {...}
}

class Grid {
    Map<int, Map<Chunk>> chunks;
    Grid new(int chunkSize) {...}
    void setPixel(int x, int y, int value) {
         getChunk(x,y).setPixel(x % chunkSize, y % chunkSize, value);//actually the modulo could be right in Chunk::setPixel and getPixel for more safety
    }
    int getPixel(int x, int y) { /*along the lines of setPixel*/ }
    private Chunk getChunk(int x, int y) {
         x /= chunkSize;
         y /= chunkSize;
         Map<Chunk> row = chunks.get(y);
         if (row == null) chunks.set(y, row = new Map<Chunk>());
         Chunk ret = row.get(x);
         if (ret == null) row.set(x, ret = new Chunk(chunkSize));
         return ret;
    }
}
</code>```

This implementation is quite naive.

For one, it creates chunks in getPixel (basically it would be fine to simply return 0 or so, if no chunks was defined for that position). Secondly it is based on the assumption, that you have a sufficiently fast and scalable implementation of Map. To my knowledge every decent language has one.

Also you will have to play with the chunk size. For dense bitmaps, a big chunk size is good, for sparse bitmaps a smaller chunk size is better. In fact for very sparse ones, a "chunk size" of 1 is the best, rendering the "chunks" themselves obsolete and reducing the data structure to an int map of an int map of pixels.

Off the shelf

Another solution might be to look at some graphics libraries. They are actually quite good at drawing one 2D buffer into another. That would mean you'd simply allocate a bigger buffer and have the original drawn into it at the according coordinates.

As a general strategy: When having a "dynamically growing memory block", it is a good idea to allocate a multiple of it, once it is used up. This is rather memory intense, but significantly cuts allocation and copying costs. Most vector implementations allocate twice their size, when it's exceeded. So especially if you go with the off-the-shelf solution, don't extend you buffer just by 1 pixel, because only one pixel was requested. Allocated memory is cheap. Reallocating, copying and releasing is expensive.

Title: Infinite Bitmap

Body:
By Hand

If memory is not a very sparse resource, I consider working in bigger chunks.

Here's some pseudo-code.

class Chunk {
    Chunk new(int size) {...}
    void setPixel(int x, int y, int value) {...}
    int getPixel(int x, int y) {...}
}

class Grid {
    Map<int, Map<Chunk>> chunks;
    Grid new(int chunkSize) {...}
    void setPixel(int x, int y, int value) {
         getChunk(x,y).setPixel(x % chunkSize, y % chunkSize, value);//actually the modulo could be right in Chunk::setPixel and getPixel for more safety
    }
    int getPixel(int x, int y) { /*along the lines of setPixel*/ }
    private Chunk getChunk(int x, int y) {
         x /= chunkSize;
         y /= chunkSize;
         Map<Chunk> row = chunks.get(y);
         if (row == null) chunks.set(y, row = new Map<Chunk>());
         Chunk ret = row.get(x);
         if (ret == null) row.set(x, ret = new Chunk(chunkSize));
         return ret;
    }
}

This implementation is quite naive.

For one, it creates chunks in getPixel (basically it would be fine to simply return 0 or so, if no chunks was defined for that position). Secondly it is based on the assumption, that you have a sufficiently fast and scalable implementation of Map. To my knowledge every decent language has one.

Also you will have to play with the chunk size. For dense bitmaps, a big chunk size is good, for sparse bitmaps a smaller chunk size is better. In fact for very sparse ones, a "chunk size" of 1 is the best, rendering the "chunks" themselves obsolete and reducing the data structure to an int map of an int map of pixels.

Off the shelf

Another solution might be to look at some graphics libraries. They are actually quite good at drawing one 2D buffer into another. That would mean you'd simply allocate a bigger buffer and have the original drawn into it at the according coordinates.

As a general strategy: When having a "dynamically growing memory block", it is a good idea to allocate a multiple of it, once it is used up. This is rather memory intense, but significantly cuts allocation and copying costs. Most vector implementations allocate twice their size, when it's exceeded. So especially if you go with the off-the-shelf solution, don't extend you buffer just by 1 pixel, because only one pixel was requested. Allocated memory is cheap. Reallocating, copying and releasing is expensive.


答:
Just a couple of points of advice:

If you implement this as an array of some integral type (or an array of arrays of ...) you probably should grow the backing array by some number of bits / pixels each time to avoid having to shift the bits as you copy them.  The down-side is that you use more space, but the proportion of wasted space drops as the bitmap gets bigger.

If you use a Map-based data structure, you can finesse the problem of growing the bitmap by simply relocating the x,y coordinate arguments of the getPixel and setPixel calls.

If you use a Map-based data structure, you only need map entries for the "ones".  The "zeros" can indicated by the absence of an entry.  This saves up a significant amount of space, especially if the bitmap is mostly zeros.

You don't need to use a Map of Maps.  You can encode an int x,y pair as a single long.  An analogous process can be used to map an array of arrays to an array.

Finally, you need to balance 3 things:

the performance of getPixel and setPixel,

the performance of the extend* operations, and

the space utilization.

Title: Infinite Bitmap


答:
Before trying anything else more complicated, and unless you cannot hold everything in memory, keep things simple and use a two dimensional array together with the information about the origin of your coordinate system. To expand it, use the same strategy like, for example, the C++ std::vector does: make a distinction between the actual size of your array and the capacity of the array, and expand the capacity in chunks whenever the limit is reached. "capacity" here should be defined in terms of intervals (from_x, to_x), (from_y,to_y).

This may need a complete reallocation of the memory from time to time, but as long as this does not happen too often, it may be fast enough for your purpose (in fact, you have to try / profile this).

Title: Infinite Bitmap