问:
Do coding puzzles make good interview questions
I am interviewing candidates for Java programmer positions.

My colleague insists in filling more than half of the interview with java coding puzzles.His view is that, if candidates are able to navigate through the loops, then they must be good.

One such example of coding puzzle is

```<code>        i=0;
        for( i=1 ; i< 10 ;i++)
        {
                if(i%3 ==0) i++; break;
                if(i%2 ==0) i++;

         }
          print(i);
</code>```

Follow up: what happens if break is removed ?

答: I've never thought coding puzzles are particularly effective at discovering whether somebody has a good knowledge of code or of problem solving. Usually I find the kind of problem soving required for them is rather different to the kind of problem solving when actually writing software. They generally have no requirement to think creatively. COntrast this with the Google type of interview question "How would you come up with a price for washing all the windows in Seatle?" This requires creativity and problem solving ability, but can be applied to any programming language you are going to use in the future.</p>


问:
Can web technologies, like PHP, HTML, and CSS, be used for desktop development?
I have to develop an application for a gas agency where a database will store consumer numbers, names, addresses, and date delivered for a town with nearly 20,000 people. I only know PHP, MySQL, CSS, jQuery, and other web based technologies. Is it possible to deliver a package to the client using these technologies that can be installed on a computer and used locally?

This application will run on a single PC for a single user. I'm familiar with tools such as XAMPP, but I do not want to run a web server locally. Both the application and database will be securely running on a particular computer. In the future, if this application must be on multiple computers, I want the database and application to be portable.

I have searched for similar questions on Stack Overflow and I did find some recommendations like Jetty, Adobe Air and the recent Web SQL database. Is PHP GTK also a viable tool for building professional applications?

I would like a recommendation specific for this kind of app.

答:
Check out CouchDB?

It is a simple, web oriented, JSON based NoSQL database.

You just need to install a single application and you have a NoSQL database with a web interface called Futon. You can easily create db-connected, lightweight web applications with html + javascript. CouchDB documents are available from web browser, and your program code (HTML + JavaScript + ...) can be like that too. And you don't need to install and configure PHP, MySQL, etc.

ContentLicense: CC BY-SA 3.0


问:
API design involving standard and custom settings
Suppose a class allows some kind of configuration that has some well-known default values but also has the option of defining a custom value. For example, suppose you want to let users configure a person's title. They can choose from a set of standard values (Mr., Mrs., Ms., etc.) but they can also specify a custom (Dr.). What is the most elegant way to put this in an API? Some examples in Java:

```<code>public class Person {
  public enum Title {MR, MRS, MS, CUSTOM};

  setTitle(Title title, String customTitle);
}
</code>```

This one is quite bad because whenever you specify anything else than Title.CUSTOM the second argument is silently ignored.

So maybe:

```<code>public class Person {
  public enum Title { MR, MRS, MS, CUSTOM};

  setTitle(Title title);
  setCustomTitle(String title);
}
</code>```

I don't really like this one either, because it's not immediately clear that calling one will overwrite the effects of the other method. Is there a more elegant interface that I'm overlooking?

答:
Is there a reason why you need the title enumeration or is this just an implementation detail?

Depending what you want to do with the api this could be a simple solution.

```<code>public class Person {
  public static final String MR = "MR";
  public static final String MRS = "MRS";
  public static final String MS= "MS";

  public void setCustomTitle(String title);
}
</code>```

Maybe it is a good idea to distinguish title from sex if this is necessary for your processing

```<code>  public enum Sex { Female, Male, };
  public void setSex(Sex sex); //Does what you'd expect
</code>```

Body:
Is there a reason why you need the title enumeration or is this just an implementation detail?

Depending what you want to do with the api this could be a simple solution.

public class Person {
  public static final String MR = "MR";
  public static final String MRS = "MRS";
  public static final String MS= "MS";

  public void setCustomTitle(String title);
}

Maybe it is a good idea to distinguish title from sex if this is necessary for your processing

  public enum Sex { Female, Male, };
  public void setSex(Sex sex); //Does what you'd expect


问:
Is using goto ever worthwhile?
goto is almost universally discouraged. Is using this statement ever worthwhile?

答: goto may be useful when porting legacy assembler code to C. In the first instance, an instruction-by-instruction conversion to C, using goto as a replacement for the assembler's branch instruction, can enable very rapid porting.

Title: Is using goto ever worthwhile?


问:
Any reference doc /model/ implementation of enforcing events dependency/ordering in distributed computing?
For example, Process P is listening to events E(A) and E(B), but to process either of the events, P needs the other event available too. Naively, when P receives either of the events, it will check if the other event is already received. If not, it can wait. But

1) this does not sound very efficient, especially when each process has many different types of events to process.

2) Also as the number of distributed processes increases to a large number, events are more tangled between processes, processes dies/restarts, etc. all these make the events handling more complicated.

So I would like to know if there are any reference doc / model/ implementations for events handling under such a distributed computing environment?

答:
You can manage this coordination using workflow/saga techniques.

Your process defines a workflow (state machine) that can be initiated on receipt of either E(A) or E(B).

For example: on receipt of E(A) your Process service initiates a workflow that begins waiting for a matching E(B) message. Subsequent receipt of E(B) message will resume the workflow originally started by E(A).

In between workflow initiation and resumption, you might consider storing workflow in persistent storage to survive termination of your Process service.

The documentation on Sagas (workflow) from NServiceBus explains this concept well.


问:
Hard-copy approaches to time tracking
I have a problem: I suck at tracking time-on-task for specific feature/defects/etc while coding them.  I tend to jump between tasks a fair bit (partly due to the inherit juggling required by professional software development, partly due to my personal tendancy to focus on the code itself and not the business process around code).

My personal preference is for a hard-copy system.  Even with gabillions of pixels of real-estate on-screen I find it terribly distracting to keep a tracking window convienient; either I forget about it or it gets in my ways.

So, looking for suggestions on time-tracking.  My only requirement is a simple system to track start/stop times per task.  I've considered going as far as buying a time-clock and giving each ticket a dedicated time-card.  When I start working on it, punch-in; when done working, punch-out.

答: I keep several cheap stopwatches, chronographs and eggtimers handy at my desk. I can always grab one to use for each individual task:

ContentLicense: CC BY-SA 2.5

Title: Hard-copy approaches to time tracking


问:
Need to make my code more readable to the other programers in my team
I am working a project in delphi and I am creating a installer for the application,
there are Three main parts.

PostgreSQL installation/uninstallation

myapplication ( setup of myapplication is created using nsi) installation/uninstallation.

Creating tables in Postgres through script(batch files).

Every thing runs fine and smoothly, but if something fails I have created a LogToFileger which will LogToFile every step of the process,

like this

```<code>LogToFileToFile.LogToFile('[DatabaseInstallation]  :  [ACTION]:Postgres installation started');
</code>```

The function LogToFileToFile.LogToFile() This will write the contents to a file. This is working nicely, but the problem is this has messed up the code as  in it has become difficult to read the code as one ca only see the LogToFileToFile.LogToFile() function call everywhere in the code

an example

```<code> if Not FileExists(SystemDrive+'\FileName.txt') then
 begin
    if CopyFile(PChar(FilePathBase+'FileName.txt'), PChar(SystemDrive+'\FileName.txt'), False) then
       LogToFileToFile.LogToFile('[DatabaseInstallation] :  copying FileName.txt to '+SystemDrive+'\ done')
       else
       LogToFileToFile.LogToFile('[DatabaseInstallation] :  copying FileName.txt to '+SystemDrive+'\ Failed');
 end;
 if Not FileExists(SystemDrive+'\SecondFileName.txt')      then
   begin
     if CopyFile(PChar(FilePathBase+'SecondFileName.txt'), PChar('c:\SecondFileName.txt'), False) then
       LogToFileToFile.LogToFile('[DatabaseInstallation] : copying SecondFileName.txt to '+SystemDrive+'\ done')
   else
       LogToFileToFile.LogToFile('[DatabaseInstallation] :  copying SecondFileName.txt to '+SystemDrive+'\ Failed');
 end;
</code>```

as you can see there are lots of LogToFileToFile.LogToFile() calls,

before it was

```<code> if Not FileExists(SystemDrive+'\FileName.txt') then
    CopyFile(PChar(FilePathBase+'FileName.txt'), PChar(SystemDrive+'\FileName.txt'), False)
 if Not FileExists(SystemDrive+'\SecondFileName.txt')      then
   CopyFile(PChar(FilePathBase+'SecondFileName.txt'), PChar('c:\SecondFileName.txt'), False)
</code>```

this is the case in my whole code now.

its difficult to read.

can any one suggest me a nice way to unclutter the calls to LogToFile?

like

Indenting the ' LogToFileToFile.LogToFile()` call

like this

```<code>   if Not FileExists(SystemDrive+'\FileName.txt') then
     begin
         if CopyFile(PChar(FilePathBase+'FileName.txt'), PChar(SystemDrive+'\FileName.txt'), False) then
        {Far away--->>}                   LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ sucessful')
   else
        {Far away--->>}                   LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ Failed');
   end;
</code>```

Separate unit like LogToFileger

This unit will have all the LogToFile messages in a switch case like this

```<code> Function LogToFilegingMyMessage(LogToFilegMessage : integer)

 begin
case  LogToFilegMessage of

1         :  LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ sucessful');
2         :  LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ Failed');
   150        :  LogToFileToFile.LogToFile(2,'[somthing] :  [ACTION]: somthing important);

end;
</code>```

so I can just call the LogToFilegingMyMessage(1) where ever required.

Can anyone tell me which is a better and cleaner approach to LogToFileging this way?

答:
One possible approach is to reduce the code by using constants.

```<code>if CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False) then
   LogBook.Log(2,'[POSTGRESQL INSTALLATION] :  [ACTION]:copying Mapannotation.txt to '+sOSdrive+'\ sucessful')
   else
   LogBook.Log(2,'[POSTGRESQL INSTALLATION] :  [ACTION]:copying Mapannotation.txt to '+sOSdrive+'\ Failed');
</code>```

would become:

```<code>if CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False) then
   Log(2, SqlInstal, Action, CopyMapSuccess, sOSdrive)
   else
   Log(2, SqlInstal, Action, CopyMapFailure, sOSdrive)
</code>```

which has a better log code/other code ratio when counting the number of characters on the screen.

This is close to what you suggested in the point 2 of your question, except that I wouldn't go so far: Log(9257) is obviously shorter than Log(2, SqlInstal, Action, CopyMapSuccess, sOSdrive), but also quite difficult to read. What is 9257? Is it a success? An action? Is it related to SQL? If you work on this codebase for the past ten years, you'll learn those numbers by heart (if there is a logic, i.e. 9xxx are success codes, x2xx are related to SQL, etc.), but for a fresh developer who discovers the codebase, short codes will be a nightmare.

You can go further by mixing the two approaches: use a single constant. Personally, I wouldn't do that. Either your constants will grow in size:

```<code>Log(Type2SuccessSqlInstallCopyMapSuccess, sOSdrive) // Can you read this? Really?
</code>```

or the constants will remain short, but not very explicit:

```<code>Log(T2SSQ_CopyMapSuccess, sOSdrive) // What's T2? What's SSQ? Or is it S, followed by SQ?
// or
Log(CopyMapSuccess, sOSdrive) // Is it an action? Is it related to SQL?
</code>```

This also has two drawbacks. You'll have to:

Keep a separate list associating log info to their respective constants. With a single constant, it will grow fast.

Find a way to enforce a single format in your team. For example, what if instead of T2SSQ, someone will decide to write ST2SQL?

Body:
One possible approach is to reduce the code by using constants.

if CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False) then
   LogBook.Log(2,'[POSTGRESQL INSTALLATION] :  [ACTION]:copying Mapannotation.txt to '+sOSdrive+'\ sucessful')
   else
   LogBook.Log(2,'[POSTGRESQL INSTALLATION] :  [ACTION]:copying Mapannotation.txt to '+sOSdrive+'\ Failed');

would become:

if CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False) then
   Log(2, SqlInstal, Action, CopyMapSuccess, sOSdrive)
   else
   Log(2, SqlInstal, Action, CopyMapFailure, sOSdrive)

which has a better log code/other code ratio when counting the number of characters on the screen.

This is close to what you suggested in the point 2 of your question, except that I wouldn't go so far: Log(9257) is obviously shorter than Log(2, SqlInstal, Action, CopyMapSuccess, sOSdrive), but also quite difficult to read. What is 9257? Is it a success? An action? Is it related to SQL? If you work on this codebase for the past ten years, you'll learn those numbers by heart (if there is a logic, i.e. 9xxx are success codes, x2xx are related to SQL, etc.), but for a fresh developer who discovers the codebase, short codes will be a nightmare.

You can go further by mixing the two approaches: use a single constant. Personally, I wouldn't do that. Either your constants will grow in size:

Log(Type2SuccessSqlInstallCopyMapSuccess, sOSdrive) // Can you read this? Really?

or the constants will remain short, but not very explicit:

Log(T2SSQ_CopyMapSuccess, sOSdrive) // What's T2? What's SSQ? Or is it S, followed by SQ?
// or
Log(CopyMapSuccess, sOSdrive) // Is it an action? Is it related to SQL?

This also has two drawbacks. You'll have to:

Keep a separate list associating log info to their respective constants. With a single constant, it will grow fast.

Find a way to enforce a single format in your team. For example, what if instead of T2SSQ, someone will decide to write ST2SQL?


答:
I would say that the idea behind option 2 is the best. However, I think the direction you took it makes things worse. The integer doesn't mean anything. When you are looking at the code, you will see something is being logged, but you don't know what.

Instead I would do something like this:

```<code>void logHelper(String phase, String message) {
   LogBook.Log(2, "[" + phase + "] :  [Action]: " + message);
}
</code>```

This retains the message structure but allows your code to be flexible. You can define constant strings as needed for the phases and only use those as the phase parameter. This allows you to be able to make change to the actual text in one place and effect everything. The other benefit to the helper function is that the important text is with the code (like it was a comment), but the text that is only important to the log file is abstracted away.

```<code>if (!FileExists(sOSdrive+'\Mapannotation.txt')) {
    if (CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False)) {
       logHelper(POSTGRESQL, 'copying Mapannotation.txt to '+ sOSdrive +'\ sucessful')
    } else {
       logHelper(POSTGRESQL, 'copying Mapannotation.txt to '+ sOSdrive +'\ Failed');
    }
}
</code>```

This isn't something that you mentioned in your question, but I noticed about your code. Your indentation is not consistent. The first time you use begin it is not indented, but the second time it is. You do a similar thing with else. I would say this is much more important than the log lines. When the indentation is not consistent, it makes it hard to scan the code and follow the flow. Lots of repetitive log lines are easy to filter out when scanning.

Title: Need to make my code more readable to the other programers in my team

Body:
I am working a project in delphi and I am creating a installer for the application,
there are Three main parts.

PostgreSQL installation/uninstallation

myapplication ( setup of myapplication is created using nsi) installation/uninstallation.

Creating tables in Postgres through script(batch files).

Every thing runs fine and smoothly, but if something fails I have created a LogToFileger which will LogToFile every step of the process,

like this

```<code>LogToFileToFile.LogToFile('[DatabaseInstallation]  :  [ACTION]:Postgres installation started');
</code>```

The function LogToFileToFile.LogToFile() This will write the contents to a file. This is working nicely, but the problem is this has messed up the code as  in it has become difficult to read the code as one ca only see the LogToFileToFile.LogToFile() function call everywhere in the code

an example

```<code> if Not FileExists(SystemDrive+'\FileName.txt') then
 begin
    if CopyFile(PChar(FilePathBase+'FileName.txt'), PChar(SystemDrive+'\FileName.txt'), False) then
       LogToFileToFile.LogToFile('[DatabaseInstallation] :  copying FileName.txt to '+SystemDrive+'\ done')
       else
       LogToFileToFile.LogToFile('[DatabaseInstallation] :  copying FileName.txt to '+SystemDrive+'\ Failed');
 end;
 if Not FileExists(SystemDrive+'\SecondFileName.txt')      then
   begin
     if CopyFile(PChar(FilePathBase+'SecondFileName.txt'), PChar('c:\SecondFileName.txt'), False) then
       LogToFileToFile.LogToFile('[DatabaseInstallation] : copying SecondFileName.txt to '+SystemDrive+'\ done')
   else
       LogToFileToFile.LogToFile('[DatabaseInstallation] :  copying SecondFileName.txt to '+SystemDrive+'\ Failed');
 end;
</code>```

as you can see there are lots of LogToFileToFile.LogToFile() calls,

before it was

```<code> if Not FileExists(SystemDrive+'\FileName.txt') then
    CopyFile(PChar(FilePathBase+'FileName.txt'), PChar(SystemDrive+'\FileName.txt'), False)
 if Not FileExists(SystemDrive+'\SecondFileName.txt')      then
   CopyFile(PChar(FilePathBase+'SecondFileName.txt'), PChar('c:\SecondFileName.txt'), False)
</code>```

this is the case in my whole code now.

its difficult to read.

can any one suggest me a nice way to unclutter the calls to LogToFile?

like

Indenting the ' LogToFileToFile.LogToFile()` call

like this

```<code>   if Not FileExists(SystemDrive+'\FileName.txt') then
     begin
         if CopyFile(PChar(FilePathBase+'FileName.txt'), PChar(SystemDrive+'\FileName.txt'), False) then
        {Far away--->>}                   LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ sucessful')
   else
        {Far away--->>}                   LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ Failed');
   end;
</code>```

Separate unit like LogToFileger

This unit will have all the LogToFile messages in a switch case like this

```<code> Function LogToFilegingMyMessage(LogToFilegMessage : integer)

 begin
case  LogToFilegMessage of

1         :  LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ sucessful');
2         :  LogToFileToFile.LogToFile(2,'[DatabaseInstallation] :  [ACTION]:copying FileName.txt to '+SystemDrive+'\ Failed');
   150        :  LogToFileToFile.LogToFile(2,'[somthing] :  [ACTION]: somthing important);

end;
</code>```

so I can just call the LogToFilegingMyMessage(1) where ever required.

Can anyone tell me which is a better and cleaner approach to LogToFileging this way?

Body:
I would say that the idea behind option 2 is the best. However, I think the direction you took it makes things worse. The integer doesn't mean anything. When you are looking at the code, you will see something is being logged, but you don't know what.

Instead I would do something like this:

void logHelper(String phase, String message) {
   LogBook.Log(2, "[" + phase + "] :  [Action]: " + message);
}

This retains the message structure but allows your code to be flexible. You can define constant strings as needed for the phases and only use those as the phase parameter. This allows you to be able to make change to the actual text in one place and effect everything. The other benefit to the helper function is that the important text is with the code (like it was a comment), but the text that is only important to the log file is abstracted away.

if (!FileExists(sOSdrive+'\Mapannotation.txt')) {
    if (CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False)) {
       logHelper(POSTGRESQL, 'copying Mapannotation.txt to '+ sOSdrive +'\ sucessful')
    } else {
       logHelper(POSTGRESQL, 'copying Mapannotation.txt to '+ sOSdrive +'\ Failed');
    }
}

This isn't something that you mentioned in your question, but I noticed about your code. Your indentation is not consistent. The first time you use begin it is not indented, but the second time it is. You do a similar thing with else. I would say this is much more important than the log lines. When the indentation is not consistent, it makes it hard to scan the code and follow the flow. Lots of repetitive log lines are easy to filter out when scanning.


答:
Looks like you need to abstract out the concept of a "LoggableAction". I'm seeing a pattern in your example where all the calls return a bool to indicate success or failure and the only difference is the log message.

It's been years since I wrote delphi so this is pretty much c# inspired pseudo-code but I would have thought you want something like

```<code>void LoggableAction(FunctionToCallPointer, string logMessage)
{
    if(!FunctionToCallPointer)
    {
        Log(logMessage).
    }
}
</code>```

Then your calling code becomes

```<code>if Not FileExists(sOSdrive+'\Mapannotation.txt') then
    LoggableAction(CopyFile(PChar(sTxtpath+'Mapannotation.txt'), "Oops, it went wrong")
</code>```

I can't remember the Delphi syntax for function pointers but whatever the implementation details, some sort of abstraction around the log routine would seem to be what you're looking for.

Body:
Looks like you need to abstract out the concept of a "LoggableAction". I'm seeing a pattern in your example where all the calls return a bool to indicate success or failure and the only difference is the log message.

It's been years since I wrote delphi so this is pretty much c# inspired pseudo-code but I would have thought you want something like

void LoggableAction(FunctionToCallPointer, string logMessage)
{
    if(!FunctionToCallPointer)
    {
        Log(logMessage).
    }
}

Then your calling code becomes

if Not FileExists(sOSdrive+'\Mapannotation.txt') then
    LoggableAction(CopyFile(PChar(sTxtpath+'Mapannotation.txt'), "Oops, it went wrong")

I can't remember the Delphi syntax for function pointers but whatever the implementation details, some sort of abstraction around the log routine would seem to be what you're looking for.


答:
Try extracting a series of little functions to handle all of the messy looking stuff.  There is a lot of repeated code that could very easily be all done in a single place. For example:

```<code>procedure CopyIfFileDoesNotExist(filename: string);
var
   success: boolean;
begin
   if Not FileExists(sOSdrive+'\'+filename') then
   begin
      success := CopyFile(PChar(sTxtpath+filename), PChar(sOSdrive+filename), False);

      Log(filename, success);
   end;
end;

procedure Log(filename: string; isSuccess: boolean)
var
   state: string;
begin
   if isSuccess then
   begin
      state := 'success';
   end
   else
   begin
      state := 'failed';
   end;

   LogBook.Log(2,'[POSTGRESQL INSTALLATION] : [ACTION]:copying ' + filename + ' to '+sOSdrive+'\ ' + state);
end;
</code>```

The trick is to look at any duplication in your code, and find ways to remove it.  Use lots of whitespace, and use the begin/end to your advantage (more whitespace, and easy to find/fold code blocks).  It really shouldn't be too difficult. These methods could be a part of your logger... it's up to you really. But that looks like a good place to start.

Body:
Try extracting a series of little functions to handle all of the messy looking stuff.  There is a lot of repeated code that could very easily be all done in a single place. For example:

procedure CopyIfFileDoesNotExist(filename: string);
var
   success: boolean;
begin
   if Not FileExists(sOSdrive+'\'+filename') then
   begin
      success := CopyFile(PChar(sTxtpath+filename), PChar(sOSdrive+filename), False);

      Log(filename, success);
   end;
end;

procedure Log(filename: string; isSuccess: boolean)
var
   state: string;
begin
   if isSuccess then
   begin
      state := 'success';
   end
   else
   begin
      state := 'failed';
   end;

   LogBook.Log(2,'[POSTGRESQL INSTALLATION] : [ACTION]:copying ' + filename + ' to '+sOSdrive+'\ ' + state);
end;

The trick is to look at any duplication in your code, and find ways to remove it.  Use lots of whitespace, and use the begin/end to your advantage (more whitespace, and easy to find/fold code blocks).  It really shouldn't be too difficult. These methods could be a part of your logger... it's up to you really. But that looks like a good place to start.


答:
When you added logging, you introduced two things:

Code became bigger because for almost every action, you added a line that logs that action (or its failure)

Log lines themselves appear to be bloated and take away from readability because they take up so much room.

Each of these has problems has its own, relatively simple solution:

Break the code up into smaller functions.  Instead of having one giant function that contains all your copies as well as log messages for error/success, you could introduce a function "CopyFile", that would copy exactly one file and logs it's own result.  That way your main code would just consist of CopyFile calls and would remain easy to read.

You could make your logger smarter.  Instead of passing in a giant string that has a lot of repetitive information, you could pass in enumerations values that would make things clearer.  Or you could define more specialized Log() functions, i.e. LogFileCopy, LogDbInsert...  Whatever you repeat a lot, consider factoring that out into its own function.

If you follow (1), you could have code that looks like this:

```<code>CopyFile( sOSDrive, 'Mapannotation.txt' )
CopyFile( sOSDrive, 'Mappoints.txt' )
CopyFile( sOSDrive, 'Mapsomethingelse.txt' )
. . . .
</code>```

Then your CopyFile() just needs few lines of code to do the action and log its result, so all your code remains concise and easy to read.

I would stay away from your approach #2 as you are detaching information that should stay together into different modules.  You are just asking for your main code to get out of sync with your log statements. But looking at LogMyMessage( 5 ), you'll never know that.

UPDATE (response to comment):
I'm not familiar with exact language you are using, so this part might have to be adapted a bit.  It seems all your log messages identify 3 things: component, action, outcome.

I think this is pretty much what MainMa suggested. Instead of passing actual string, define  constants (in C/C++/C#, they would be part of enum enumeration type). So for example for components, you might have: DbInstall, AppFiles, Registry, Shortcuts...  Anything that make the code smaller will make it easy to read.

It would also help if your language supported variable parameter passing, not sure if that's possible.  So for example if action is "FileCopy", you could define that action to have two additional user parameters: file name and destination directory.

So your file copying lines would look something like this:

```<code>Bool isSuccess = CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False)
LogBook.Log( DbInstall, FileCopy, isSuccess, 'Mapannotation.txt', sOSDrive )
</code>```

*note, there's also no reason to copy/paste the log line twice if you can store the result of the operation in a separate local variable and just pass that variable into Log().

You see the theme here, right?  Less repetitive code -> more readable code.

Body:
When you added logging, you introduced two things:

Code became bigger because for almost every action, you added a line that logs that action (or its failure)

Log lines themselves appear to be bloated and take away from readability because they take up so much room.

Each of these has problems has its own, relatively simple solution:

Break the code up into smaller functions.  Instead of having one giant function that contains all your copies as well as log messages for error/success, you could introduce a function "CopyFile", that would copy exactly one file and logs it's own result.  That way your main code would just consist of CopyFile calls and would remain easy to read.

You could make your logger smarter.  Instead of passing in a giant string that has a lot of repetitive information, you could pass in enumerations values that would make things clearer.  Or you could define more specialized Log() functions, i.e. LogFileCopy, LogDbInsert...  Whatever you repeat a lot, consider factoring that out into its own function.

If you follow (1), you could have code that looks like this:

CopyFile( sOSDrive, 'Mapannotation.txt' )
CopyFile( sOSDrive, 'Mappoints.txt' )
CopyFile( sOSDrive, 'Mapsomethingelse.txt' )
. . . .

Then your CopyFile() just needs few lines of code to do the action and log its result, so all your code remains concise and easy to read.

I would stay away from your approach #2 as you are detaching information that should stay together into different modules.  You are just asking for your main code to get out of sync with your log statements. But looking at LogMyMessage( 5 ), you'll never know that.

UPDATE (response to comment):
I'm not familiar with exact language you are using, so this part might have to be adapted a bit.  It seems all your log messages identify 3 things: component, action, outcome.

I think this is pretty much what MainMa suggested. Instead of passing actual string, define  constants (in C/C++/C#, they would be part of enum enumeration type). So for example for components, you might have: DbInstall, AppFiles, Registry, Shortcuts...  Anything that make the code smaller will make it easy to read.

It would also help if your language supported variable parameter passing, not sure if that's possible.  So for example if action is "FileCopy", you could define that action to have two additional user parameters: file name and destination directory.

So your file copying lines would look something like this:

Bool isSuccess = CopyFile(PChar(sTxtpath+'Mapannotation.txt'), PChar(sOSdrive+'\Mapannotation.txt'), False)
LogBook.Log( DbInstall, FileCopy, isSuccess, 'Mapannotation.txt', sOSDrive )

*note, there's also no reason to copy/paste the log line twice if you can store the result of the operation in a separate local variable and just pass that variable into Log().

You see the theme here, right?  Less repetitive code -> more readable code.


问:
When stuck, how quickly should one resort to Stack Overflow?
I'm self-learning iOS development through the iTunes U CS193p course, and I often find myself stuck. I've been trying to get unstuck myself, but it might take me hours and hours to figure out what I'm doing wrong, be it missing a method or not really getting a whole concept like delegation.

I'm worried that I might be wasting too much time, and I'd be better off going to Stack Overflow shortly after I get stuck so I can move on.

In your experience, does quickly asking on Stack Overflow hamper the learning process or improve it?

答:
My only addition to everyone else's great answers:

TYPING UP your question into the StackOverflow question interface is a great way to make sure you're thinking through it fully. I can't begin to tell you how many questions I've answered for myself in the process of laying it out clearly enough to ask it properly. The questions I've started and not submitted VASTLY outnumbers those I've actually asked.

So, I'd say go ahead and ask (after searching, of course), just don't be attached to actually hitting "Submit".


问:
How do I efficiently store all OpenStreetMap data in an indexed way?
I have a PBF file that contains the following information about a country:

Nodes, each with their own longitude, latitude and properties; used to store points in a 2D space.

Ways, each with their properties, they are connected through nodes; used to store roads, boundaries.

While this file is only 80 MB in its compressed form, it's 592 MB when uncompressed and stored in a DB.

Yeah, and that's only for one country, Belgium. Imagine storing France, Germany and Italy alongside.

Let's take a single highway for example, from Antwerp through Brussels to Charleroi. This would consist of a ton of nodes to store all the turns in the highway, but do I need all these turns? I doubt it.

Let me tell you what I want to be able to do:

I want to view the map at different zooming levels; major cities, minor cities and street level at least.

I want to be able to get routing information between two points.

I want to be able to compute the nearest road to my GPS location.

Search for a location, by means of an index in the database.

But most importantly, the database shouldn't be too big as it will be stored on a mobile device.

So, I thought about a combination of two techniques:

Image tiles for viewing purposes, to working around storing/processing all the individual nodes.

Storing the endpoints of roads for routing information, alongside information about the road.

The problem with this is that I can't compute the nearest road to my GPS location with only this information; imagine that a bend in a highway, I can't determine that I'm on the highway with just the two endpoints. I was thinking about storing intermediate nodes between endpoints but that would be very costly to generate, I think. Also, determining the endpoints of roads (that are like a T-split) is most likely not even that easy as I need to figure out whether I need to store the midpoint at the top of that T-split or not.

So, viewing is easy using image tiles; but I can't find an easy way to do routing and GPS location finding, what kind of storage technique should I be looking into? I find it a bit inconvenient that a 80 MB file turns into a database of 592 MB, I want to reduce that size a much as possible...

What can I do to do this as efficiently as possible? In terms of disk and CPU. I'm targeting a WP7...

答:
It seems to me that the main issue is only including nodes that add significant information about a road.

i.e. without your GPS requirement, you could just store nodes at junctions and endings (which I think you call start/end nodes). Obviously including weight/costs etc.

One way I can think of approaching this is to first, add all start/end nodes. This is the minimum needed. Obviously this doesn't account for winding roads.

Then, for every road (defined as ending to junction or junction to junction) do the following:

Loop through all intermediate nodes and work out the minimum distance from each node to the road as defined by nodes included so far (to start with only the start and end).

If the sum of the above is larger than (some constant threshold * number of intermediate nodes) we need to add intermediate nodes. If not, exit the loop.

To add intermediate nodes find the node that had the largest distance from the current representation of the road and add it.


问:
What things do I need to become expert ASP.net MVC
I graduated in computer science. I had pretty good knowledge in Java. I have about a year experiences in ASP.net C# Web form. What other things do I need to know if I want become expert in ASP.net MVC which I able to do a complex eCommerce website?</p>

答:
In my opinion, what is your main purpose of your project, is that to conquer a very complex eCommerce website, if so, you should try another server side technology like JSP, Django or Ruby on Rails. They are more suitable. ASP best appropriate for small and medium project.

If you still decide to learn ASP.NET with MVC Pattern.
First, you should understand basic info about HTML, CSS, XML (if any), Client Side Scripting like JavaScript (these are the very important thing you need to know about web technology).

And then, you should know about MVC Pattern (supposed you know basic about ASP.NET) You can loo kup more closely the MVC Pattern in any Design Pattern Books to understand how it works.

After that, you should try to take part in more and more projects, with real practice, you gradually become an expert in ASP.NET. Just remember: "Practice makes perfect"

OwnerDisplayName: Phạm Sỹ Toàn


问:
Alternatives to time tracking methodologies
Question first: What are some feasible alternatives to time tracking for employees in a web/software development company, and why are they better options

Explanation:

I work at a company where we work like this. Everybody is paid salary. We have 3 types of work, Contract, Adhoc and Internal (Non billable). Adhoc is just small changes that take a few hours and we just bill the client at the end of the month. Contracts are signed and we have this big long process, the usual.

We figure out how much to charge by getting an estimation of the time involved (From the design and the developers), multiplying it by our hourly rate and that's it. So say we estimate 50 hours for a website. We have time tracking software and have to record the time in 15 we spend on it (7:00 to 7:15 for example), the project name, and give it some comments.

Now if we go over the 50 hours, we are both losing money and are inefficient.

Now that I've explained how the system works, my question is how else can it be done if a better method exists (Which I'm sure one must). Nobody here likes the current system, we just can't find an alternative. I'd be more than willing to work after hours longer hours on a project to get it done in time, but I'm much inclined to do so with the current system. I'd love to be able to sum up (Or link) to this post for my manager to show them why we should use abc system instead of this system.

答:
Software estimates are always difficult.  Software is a creative business, and creativity waxes and wanes.  I'm just starting to bounce back after a week of severe exhaustion--the other night it took me hours to do a task that should have been 15-30 minutes...

Also consider that each developer has different estimating abilities.  More disciplined or senior developers will tend to be more accurate and more junior or undisciplined developers are less accurate.  Also, their accuracy changes over time (not always for the better).

In my personal consulting experience I try to blend a realistic estimate with a ceiling.  Basically saying "I expect this feature to take 7-10 hours, but could reach 18--at most, even if it takes 40 hours, you will be billed for 18".  Usually this type of approach is new to clients and some flat-out reject it with "give me a firm price"--those clients get the ceiling estimate (or I politely decline their business).  For clients that accept this approach, they understand that I'll honestly track time, and their actual final bill will reflect my time-spent (but won't exceed my ceiling).  Essentially this is a lean-approach with a guarantee added; and the customer is aware that any changes to requirements introduces changes to the estimates.

Overall that approach has worked well for clients willing to accept it.  My personal goal is to gain their trust and repeat business, so it's in my interest to be honest and try to come in well under the ceiling--and it's in their interest to be helpful in keeping me under my estimates (by avoiding uncertainty, late changes, etc--I revise estimates if changes are anything beyond minor).

If you haven't, I would suggest reading The Mythical Man Month


问:
VisualVM Sampling & Accuracy
It's been said in other questions that jvisualvm sampling works as a "lightweight" profiling tool by calculating metrics directly from Java stack frames.

Its almost unanimously agreed that such a technique is faster but not as accurate in terms of its "timings". My question: why is this method not as accurate? And, what is it not as accurate as (as opposed to what? Are there more precise profiling techniques?)?

答:
There are a few factors I am aware of:

Look at the javadoc of System.currentTimeMillis() and note what it says about the Operating System granularity.  For even more fun, look at the source code of that method and see how it rounds to a millisecond. A similar rule applies for  Java's nanosecond support, look at the source code to see how it is actually used and you might be surprised.

There are still gaps where there are no Java APIs to measure certain things, e.g.  Clock counters on a CPU (which we're working on with jpcm) and APIs into the running GC itself.

HTH a little.

Title: VisualVM Sampling & Accuracy


答: Depends on the language. It's still widely used in Cobol programming, for example. I've also worked on a Barionet 50 device, whose firmware programming language is an early BASIC dialect that of course requires you to use Goto.</p>

Title: Is using goto ever worthwhile?

Body: goto is almost universally discouraged. Is using this statement ever worthwhile?


问:
How to react to wrong/not answered questions during interview?
Today I have held my first interview with potential interns.
While this has been mostly open questions, I have had some trivial programming tasks for them:

Write a function that returns true if triangle sides (all integers) a, b and c can represent a right triangle.

FizzBuzz.

Calculate the Nth element of Fibonacci using recursion (if they didn't know what Fibonacci was, I would even write them the definition F(n) = F(n-1) + F(n-2); F(1) = 1; F(0) = 1).

Implement structure List for integer and write function to reverse it.

These are obviously very easy tasks and I was not prepared for someone not to solve them.

How should I act when they struggle with these questions? Should I give up the answer? Give tip by tip (I did that and ended up solving the problem myself)? Or just move on (or maybe just stop) with the interview?

ps. By having problems with questions, I don't mean like having a bug, I mean if they can't even get started. This was a case with Fibonacci and List questions.

答:
Try to be nice on them. By your questions it is seen, that you are not trying to be nice even here. Do you think everybody should know this "fizzbuzz" term? Or we should search the net because you were lazy to write it yourself? On the contrary, I think, everybody here knows what the right triangle is.

What is "structure List"? I don't know. I know "the List structure".  What does it mean: List for integer? List of integers you mean? I too, wouldn't know how to start. And please, don't talk you are not English. Me too. And even I hadn't ever been to an English-speaking country. You surely know that integer in plural will be integers. If you are not trying to be understandable with your equals here, I can imagine how you are doing there.

Any literate programmer knows that Fibonacci row is a book example of what should not be done by recursion. Are you testing them for ability to oppose you or for coding skills? Do your job and find a better example for testing skills in using recursion.

"Ability to work under stress" for a programmer means he could work for nights when it is necessary. But if you want to have good programmers, they would wait that their chief is a very nice, understanding and helpful fellow. If you are not, you'll never have good programmers. They are not alpha-rat-males.  If they will feel any agression, they will simply close in their shells and will do nothing.

So, my answer is: be better prepared yourself.

P.S. You are a manager already, so, you really should hold stress.


问:
Real world implementation of functional programming?
I am trying to acquaint myself with different types of languages to understand the areas in which each one of them is extremely good at. So far, I have dabbled into C - a procedural language, C++ & java - static typed Object Oriented languages and groovy - a dynamic typed Object Oriented language.

Every programming language has probably been started to answer a need. And I presume every language is extremely good at at least one thing because of which it becomes a standard in a specific area or field. Like C, C++ have become standard in areas like browser or game development. Python in the Linux world for its easy scripting ability, Java in the enterprise world, etc.

Now I am interested to learn a functional programming language like Clojure or Lisp. So, where are functional programming languages used in real world scenarios? I don't think that one would use Clojure or Lisp for developing applications or UIs. So on what kind of projects should I indulge into after going through the basic tutorials and learning resources to get a brief understanding about the implementation of functional programming? And do you strongly recommend on One language in specific, like say clojure?

答:
There is a great lecture series on Functional Programming by Stanford University.You can check them on YouTube.

I would advise you to look into Scheme rather than LISP. Scheme is a modified version of Lisp with further enhancements. Scheme is mostly used for academic and training pourposes. It is a great language if you like to do research in thoretical compueter science.

Applications:

Google App Inventor for Android uses Scheme, where Kawa is used to compile the Scheme code down to byte-codes for the Java Virtual Machine running on Android devices.
Elk Scheme is used by Synopsys as a scripting language for its technology CAD (TCAD) tools.

FYI: Usage of Scheme


答:
"How quickly" is going to be, by its nature, subjective. Everyone's going to have a slightly different opinion.

If you cannot discover the cause of your problem in about 5 minutes of looking at the actual code, I would at least Google it. If a good search doesn't have the answers, then I would start writing your question on SO.

Keep in mind that it's OK not to actually post that question; there have been times when, in putting the question into written words, the solution has presented itself and I didn't have to actually put it to you guys.

Title: When stuck, how quickly should one resort to Stack Overflow?

Body:
I'm self-learning iOS development through the iTunes U CS193p course, and I often find myself stuck. I've been trying to get unstuck myself, but it might take me hours and hours to figure out what I'm doing wrong, be it missing a method or not really getting a whole concept like delegation.

I'm worried that I might be wasting too much time, and I'd be better off going to Stack Overflow shortly after I get stuck so I can move on.

In your experience, does quickly asking on Stack Overflow hamper the learning process or improve it?


问:
How to avoid throwing vexing exceptions?
Reading Eric Lippert's article on exceptions was definitely an eye opener on how I should approach exceptions, both as the producer and as the consumer. However, I'm still struggling to define a guideline regarding how to avoid throwing vexing exceptions.

Specifically:

Suppose you have a Save method that can fail because a) Somebody else modified the record before you, or b) The value you're trying to create already exists. These conditions are to be expected and not exceptional, so instead of throwing an exception you decide to create a Try version of your method, TrySave, which returns a boolean indicating if the save succeeded. But if it fails, how will the consumer know what was the problem? Or would it be best to return an enum indicating the result, kind of Ok/RecordAlreadyModified/ValueAlreadyExists? With integer.TryParse this problem doesn't exist, since there's only one reason the method can fail.

Is the previous example really a vexing situation? Or would throwing an exception in this case be the preferred way? I know that's how it's done in most libraries and frameworks, including the Entity framework.

How do you decide when to create a Try version of your method vs. providing some way to test beforehand if the method will work or not? I'm currently following these guidelines:

If there is the chance of a race condition, then create a Try version. This prevents the need for the consumer to catch an exogenous exception. For example, in the Save method described before.

If the method to test the condition pretty much would do all that the original method does, then create a Try version. For example, integer.TryParse().

In any other case, create a method to test the condition.

答:
In your example, if the ValueAlreadyExists situation can be easily checked, it should be checked and an exception could be raised before attempting the Save, I don't think a Try should be necessary in this situation. The race condition is harder to check ahead of time, so wrapping the Save in a Try in this case is probably a very good idea.

In general, if there's a condition that I think is very likely (such as NoDataReturned, DivideByZero, etc...) OR is very easy to check for (such as an empty collection or a NULL-value), I try to check for it ahead of time and deal with it before I ever get to the point where I'd have to catch an exception. I admit it's not always easy to know these conditions ahead of time, sometimes they only appear when the code is under rigourous testing.

ContentLicense: CC BY-SA 4.0


答:
You may want to have a look at Hume.

From the The Hume Programming Language page:

Hume (Higher-order Unified Meta-Environment) is a strongly typed, mostly-functional language with an integrated tool set for developing, proving and assessing concurrent, safety-critical systems. Hume aims to extend the frontiers of language design for resource-limited systems, including real-time embedded and safety-critical systems, by introducing new levels of abstraction and provability.

From the wikipedia Hume page:

Hume is a functionally-based programming language developed at the University of St Andrews and Heriot-Watt University in Scotland, and named after the 18th Century philosopher David Hume. It targets real-time embedded systems, aiming to produce a design that is both highly abstract, yet which will still allow precise extraction of time and space execution costs, so allowing programs to be written that will execute under guaranteed bounded time and space constraints.

Hume is unusual in combining functional programming ideas with ideas from finite state automata. Automata are used to structure communicating programs into a series of "boxes", where each box maps inputs to outputs in a purely functional way using high-level pattern-matching. It is also unusual in being structured as a series of levels, each of which exposes different machine properties, which is highly unusual.

Title: Real world implementation of functional programming?

Body:
I am trying to acquaint myself with different types of languages to understand the areas in which each one of them is extremely good at. So far, I have dabbled into C - a procedural language, C++ & java - static typed Object Oriented languages and groovy - a dynamic typed Object Oriented language.

Every programming language has probably been started to answer a need. And I presume every language is extremely good at at least one thing because of which it becomes a standard in a specific area or field. Like C, C++ have become standard in areas like browser or game development. Python in the Linux world for its easy scripting ability, Java in the enterprise world, etc.

Now I am interested to learn a functional programming language like Clojure or Lisp. So, where are functional programming languages used in real world scenarios? I don't think that one would use Clojure or Lisp for developing applications or UIs. So on what kind of projects should I indulge into after going through the basic tutorials and learning resources to get a brief understanding about the implementation of functional programming? And do you strongly recommend on One language in specific, like say clojure?


问:
Computed Values and Simple Reads - A nagging pain for my Domain Driven Designs!
The problem I continually face is how to deal with computed values driven by domain logic while still working efficiently against the data store.

Example:

I'm returning a list of Products from my repository via a service. This list is limited by pagination info from request DTO sent by the client. In addition, the DTO specifies a sort parameter (a client-friendly enum).

In a simple scenario, everything works great: the service sends paging and sorting expressions to the repo and the repo issues an efficient query to the DB.

That all breaks down, however, when I need to sort on values generated in memory from my domain model. For instance the Product class has an IsExpired() method that returns a bool based on business logic. Now I can't sort and page at the repo level --it would all have be done in memory (inefficient) and my service would have to know the intricacies of when to issue these params to the repo and when to perform sorting/paging itself.

The only pattern that seems to make sense to me is to store the state of the entity in the db (make IsExpired() a readonly field and update it via the domain logic before saving). If I separate this logic into a separate "read model/dto" and "reporting" repository, I'm making my model more anemic than I'd like to.

BTW, every example I've seen out there for computations like this really seems to lean on in-memory processing and glossing over the fact that it is far less efficient in the long run. Maybe I'm prematurely optimizing, but that just doesn't sit right with me.

I'd love to hear how others have dealt with this as I'm sure it's common on nearly project involving DDD.

答:
SPECIFICATION

I know you've already accepted an answer, but, you asked about DDD, and the exact match for this is what Evans calls a 'specification':

direct google books link

If that link doesn't work check for the book in these results

It's page 226 if you have the book.

On page 227 are 3 uses for specifications: Validation, Seletion, Building a new special object. Yours is 'selection' - IsExpired.

Another thing about the 'specificaiton' concept is that it admits that - for efficiency's sake - you may need one version of code to operate on the in-memory objects, and another version of the code to efficiently query the repository without having to first get all the objects into memory.

In a simple world, this would mean putting a SQL version in your repository and an objects version in your model, of course that has drawbacks. The logic is in 2 places (bad, somebody's going to forget to update on of those places) and there is domain logic in your repository.

So the answer is to put both sets of logic in a specification. The in-memory version, obviously, but a repository version, too. If you are using for example n-hibernate you can use its built-in query language for the repository version.

Otherwise you'll have to create a special repository method for this specification that is used from the specification object. Calls for collecitons of objects matching the specification would go thru the specification, not the repository. And at least the code screams 'i'm in 2 places, don't forget it' to future maintainers. There is a wonderful example on page 231-232 for a solving very similar problem.

The specification is an 'allowed' leakage/slippage of the 'purity' of DDD. It still might not serve your needs for a variety of purposes. For example, the ORM might generate bad SQL; there might be too much extra coding. So you might have to call repository methods such that it's almost like putting SQL in the specification. A bad thing of course. But don't forget, your program has to work- at a reasonable speed. It doesn't have to win a DDD purity prize. So a reality of switching datastores might mean old fashioned surgury thoughout the program. Also a bad thing. But not as bad as a slow (aka SUCKing) program. If running out of the box on various DBs is a reality, obviously, you'll be duplicating business rules for each datastore for each specification. At least you have your finger on the matter and you can make use of the strategy pattern when you swap repositories. But if you're using a specific DB already remember YAGNI.

Regarding CQRS: Fowler's quote by pdr above still holds true here: "having the same conceptual model for commands and queries leads to a more complex model that does neither well" ... and you may need to use CQRS or similar. But it is much more expensive from a development and maintainence standpoint. If you are a packages vendor in competition with others, it might pay. If you're writing a custom LOB app for one customer, shooting for perfection is a poor choice. You need to decide if the value in having a completely or mostly double model is worth the extra effort. Specification is a good compromise because it allows you to make this separation in just one little part of the program that needs it, with the (development) speed and simplicity of one model. Good luck!


答:
Suppose you have a Save method that can fail because a) Somebody else modified the record before you, or b) The value you're trying to create already exists. These conditions are to be expected and not exceptional, so instead of throwing an exception you decide to create a Try version of your method, TrySave, which returns a boolean indicating if the save succeeded. But if it fails, how will the consumer know what was the problem?

Good question.

The first question that comes to my mind is: if the data is already there then in what sense did the save fail? It sure sounds like it succeeded to me. But let's assume for the sake of argument that you really do have many different reasons why an operation can fail.

The second question that comes to my mind is: is the information you wish to return to the user actionable?  That is, are they going to make some decision based on that information?

When the "check engine" light comes on, I open up the hood, verify that there is an engine in my car that is not on fire, and take it to the garage. Of course at the garage they have all kinds of special purpose diagnostic equipment that tells them why the check engine light is on, but from my perspective, the warning system is well designed. I do not care whether the problem is because the oxygen sensor is recording an abnormal level of oxygen in the combustion chamber, or because the idle speed detector is unplugged, or whatever. I'm going to take the same action, namely, let someone else figure this out.

Does the caller care why the save failed? Are they going to do anything about it, other than either give up or try again?

Let's assume for the sake of argument that the caller really is going to take different actions depending on the reason why the operation failed.

The third question that comes to mind is: is the failure mode exceptional? I think you might be confusing possible with unexceptional. I would think of two users attempting to modify the same record at the same time as an exceptional-but-possible situation, not a common situation.

Let's assume for the sake of argument that it is unexceptional.

The fourth question that comes to mind is: is there a way to reliably detect the bad situation ahead of time?

If the bad situation is in my "exogenous" bucket, then, no. There's no way to reliably say "did another user modify this record?" because they might modify it after you ask the question. The answer is stale as soon as it is produced.

The fifth question that comes to mind is: is there a way to design the API so that the bad situation can be prevented?

For example, you could make the "save" operation require two steps. Step one: acquire a lock on the record being modified. That operation either succeeds or fails and so can return a Boolean. The caller can then have a policy about how to deal with failure: wait a while and try again, give up, whatever.  Step two: once the lock is acquired, do the save and release the lock. Now the save always succeeds and so there is no need to worry about any kind of error handling. If the save fails, that is truly exceptional.

Title: How to avoid throwing vexing exceptions?

Body:
Reading Eric Lippert's article on exceptions was definitely an eye opener on how I should approach exceptions, both as the producer and as the consumer. However, I'm still struggling to define a guideline regarding how to avoid throwing vexing exceptions.

Specifically:

Suppose you have a Save method that can fail because a) Somebody else modified the record before you, or b) The value you're trying to create already exists. These conditions are to be expected and not exceptional, so instead of throwing an exception you decide to create a Try version of your method, TrySave, which returns a boolean indicating if the save succeeded. But if it fails, how will the consumer know what was the problem? Or would it be best to return an enum indicating the result, kind of Ok/RecordAlreadyModified/ValueAlreadyExists? With integer.TryParse this problem doesn't exist, since there's only one reason the method can fail.

Is the previous example really a vexing situation? Or would throwing an exception in this case be the preferred way? I know that's how it's done in most libraries and frameworks, including the Entity framework.

How do you decide when to create a Try version of your method vs. providing some way to test beforehand if the method will work or not? I'm currently following these guidelines:

If there is the chance of a race condition, then create a Try version. This prevents the need for the consumer to catch an exogenous exception. For example, in the Save method described before.

If the method to test the condition pretty much would do all that the original method does, then create a Try version. For example, integer.TryParse().

In any other case, create a method to test the condition.


问:
Programming with a group of people I've never met
I've been assigned a group project from my AP computer science class, and I am required to work with three other people. I've never talked to them before, I have no idea their skill level, and all I have is their email address. The assignment, summed up, is this:

"As a team you will complete a minimum of three Modules to a Class...."

I going to try and become "Team captain" because none of them have attempted to contact each other but I am curious: how to go about this? I've emailed them and asked them if there are any methods of communication they prefer over emailing each other, but once we actually start the project I'll have to figure out who is doing what.

What should I do? How do I "take charge" and lead three people that I've never met?

Here is an excerpt of the actual assignment:

Therefore you will need to discuss the various roles each team member
  will take in this project early in the week.  You can communicate via
  Pronto (or Blackboard IM), email, a wiki, a google group, blog or any
  other method that you see fit. If a group member does not engage the
  group by the end of week let your instructor know and they will
  provide additional guidance.

  ...

  Also due at the end of a project will be a team evaluation in which you will rate each team members contribution to the completion of this project along with a suggested grade.

Edit: Many people suggested that I meet them in a coffee shop, or something like that. Only problem is, all of us are in different states. I also figured out one of them isn't allowed to use Facebook/Skype/twitter, so I have to resort to messaging them over yahoo messenger and emails.

答:
Do any of you have experience with working with a group of people you've never met online, and you don't get to meet them in person but must complete a project together?

Add in underbudgeting, ridiculous deadlines and getting sold down the river by marketing and this sounds like roughly 65% of software development projects in the real world.

You'd probably be best served by getting folks to volunteer for parts they would be interested in doing rather than taking charge unilaterally and assigning tasks. They are all probably sitting there thinking about how they should take charge. Or how they can get some poor sod who cares too much to do all the group work so they can ride on his grade.


问:
What are the practical uses of Windows Services?
I am new to working with Windows Services. Although I have learnt to create  Windows Services in VS2010  I would like to know some practical ways in which windows services could be used?

I tried Googling with the current context in mind only to find more tutorials on how to create Windows Services.

EDIT on Bounty Offer:

All the answers are great but I was looking for more practical examples on windows services and their implications? This will help developers know when it is appropriate to use them with the case study.

答:
An interactive program, like a winform or WPF, is something you want a user to open, interact with, and close.  A scheduled Task is something you want to run in the background as specific times - maybe just start up, do something, and stop.  A Windows Service is something you want to run all the time in the background.

Some advantages of a Windows Service is that it runs no matter which user is logged in (or even if no users are logged in) and it can be set to start running as soon as the computer boots up, which can be really useful if the system is rebooted.

I've usually used services when I have to monitor something like a folder or email inbox.


答:
You say real-world functional programming, I think Erlang.

Erlang is a programming language used to build massively scalable soft
  real-time systems with requirements on high availability. Some of its
  uses are in telecoms, banking, e-commerce, computer telephony and
  instant messaging.

http://www.erlang.org/


答: In addition to a clock, check out the Task Progress Tracker (pdf) by David Seah.</p>

Title: Hard-copy approaches to time tracking

Body:
I have a problem: I suck at tracking time-on-task for specific feature/defects/etc while coding them.  I tend to jump between tasks a fair bit (partly due to the inherit juggling required by professional software development, partly due to my personal tendancy to focus on the code itself and not the business process around code).

My personal preference is for a hard-copy system.  Even with gabillions of pixels of real-estate on-screen I find it terribly distracting to keep a tracking window convienient; either I forget about it or it gets in my ways.

So, looking for suggestions on time-tracking.  My only requirement is a simple system to track start/stop times per task.  I've considered going as far as buying a time-clock and giving each ticket a dedicated time-card.  When I start working on it, punch-in; when done working, punch-out.


答:
The leader of this project will be the person who steps up and takes charge at the beginning.

This applies to most things in life - not just software development. When everybody else is running around like chickens with no heads, the person who thinks things through, steps forward and says, "This is what we're going to do and this how we're going to do it." is usually the person looked to as the leader for the rest of the project. Bear in mind that by doing this you are taking responsibility for the ultimate success or failure of the project.

You want to lead this project? Here's a couple of things you can start doing right away to make a big impact.

Use a project management tool like Trello and send invites to everybody and start assigning parts of the project out to people.

Generate a bug database and start adding tasks and bugs - again, just start assigning.

Set up a version control repository and check in a good initial chunk of code that everyone can work from. Refuse to deal with any other form of code control.

Offer to help people get going with development by showing them how to use the version control system and bug database.

Send out weekly emails detailing the status of the project and the progress of the previous week.

None of these steps are particularly hard, or time consuming, but they will be huge time savers down the road. Furthermore, it will get your team talking to each other, and get them used to seeing you in charge.

Title: Programming with a group of people I've never met

Body:
I've been assigned a group project from my AP computer science class, and I am required to work with three other people. I've never talked to them before, I have no idea their skill level, and all I have is their email address. The assignment, summed up, is this:

"As a team you will complete a minimum of three Modules to a Class...."

I going to try and become "Team captain" because none of them have attempted to contact each other but I am curious: how to go about this? I've emailed them and asked them if there are any methods of communication they prefer over emailing each other, but once we actually start the project I'll have to figure out who is doing what.

What should I do? How do I "take charge" and lead three people that I've never met?

Here is an excerpt of the actual assignment:

Therefore you will need to discuss the various roles each team member
  will take in this project early in the week.  You can communicate via
  Pronto (or Blackboard IM), email, a wiki, a google group, blog or any
  other method that you see fit. If a group member does not engage the
  group by the end of week let your instructor know and they will
  provide additional guidance.

  ...

  Also due at the end of a project will be a team evaluation in which you will rate each team members contribution to the completion of this project along with a suggested grade.

Edit: Many people suggested that I meet them in a coffee shop, or something like that. Only problem is, all of us are in different states. I also figured out one of them isn't allowed to use Facebook/Skype/twitter, so I have to resort to messaging them over yahoo messenger and emails.


答:
You can write your question early but you shouldn't post it until you have properly researched the source of your problem. Write the things you have eliminated and how you eliminated them. You should also check for other similar questions and if you really want to post your question, explain why this is not the same question.

If you do that properly you will find that many times you will solve your own problem.


答:
First thing to do in cases like this is to establish an issue tracker and learn how to use it.

For a more fundamental introduction on how to handle development like you describe, my favorite reference goes for Martin Fowler's article Using an Agile Software Process with Offshore Development. This article outlines basics and advanced concepts of setting up distributed team communication:

```<code>Use Continuous Integration to Avoid Integration Headaches
Have Each Site Send Ambassadors to the Other Sites
Use Contact Visits to build trust
Don't Underestimate the Culture Change
Use wikis to contain common information
Use Test Scripts to Help Understand the Requirements
Use Regular Builds to Get Feedback on Functionality
Use Regular Short Status Meetings
Use Short Iterations
Use an Iteration Planning Meeting that's Tailored for Remote Sites
When Moving a Code Base, Bug Fixing Makes a Good Start
Separate teams by functionality not activity
Expect to need more documents.
Get multiple communication modes working early
</code>```

For your project you sure won't be able to follow all the tips and tricks mentioned there (eg there likely be no Ambassadors nor Contact Visits for you :) but it is worth studying anyway.

For many teams having all of above would be an overkill for sure. Still, I find it really helpful to have a comprehensive checklist like that - so that even skipped items are checked and have clearly documented reasons for rejection - just to make sure nothing important was missed.

Body:
First thing to do in cases like this is to establish an issue tracker and learn how to use it.

For a more fundamental introduction on how to handle development like you describe, my favorite reference goes for Martin Fowler's article Using an Agile Software Process with Offshore Development. This article outlines basics and advanced concepts of setting up distributed team communication:

Use Continuous Integration to Avoid Integration Headaches
Have Each Site Send Ambassadors to the Other Sites
Use Contact Visits to build trust
Don't Underestimate the Culture Change
Use wikis to contain common information
Use Test Scripts to Help Understand the Requirements
Use Regular Builds to Get Feedback on Functionality
Use Regular Short Status Meetings
Use Short Iterations
Use an Iteration Planning Meeting that's Tailored for Remote Sites
When Moving a Code Base, Bug Fixing Makes a Good Start
Separate teams by functionality not activity
Expect to need more documents.
Get multiple communication modes working early

For your project you sure won't be able to follow all the tips and tricks mentioned there (eg there likely be no Ambassadors nor Contact Visits for you :) but it is worth studying anyway.

For many teams having all of above would be an overkill for sure. Still, I find it really helpful to have a comprehensive checklist like that - so that even skipped items are checked and have clearly documented reasons for rejection - just to make sure nothing important was missed.


答:
Jarrod Nettles' answer pretty much summarises a lot what I was going to suggest, so I'll throw in some of what worked in my recent experiences in a similar situation.

I would suggest finding some way to talk with them vocally, rather than by email. If you're not in the same area, get them all on Skype. If you're in the area, meet them at a coffee shop or something. Speaking in person in initial meetings will lead to you actually making decisions and getting work done then and there; email threads allow those who're shy or often not at their computer to hold up the process - we all know how lazy students can be!

In your first meeting, I would try to get to know your group over trying to get on with the project - but don't ignore the project! 10 or 20 minutes spent ice breaking is probably enough amongst 4 people.

When it comes to talking about the project, I would suggest running through what you think the project involves. I think it's important you make it clear this is your understanding, and not a case of you telling them exactly what to do. Everybody should be able to throw their thoughts and ideas in to the ring if they have any, and you should come away from that initial meeting with a decent enough understanding of what you, as a group, feel the project entails.

In future (regular) meetings, you can start to look at different bits of the project in more detail; look at what needs doing exactly, what resources and how much time will be needed and who can do what. Split the piece up further if necessary. Perhaps try set some soft deadlines?


答:
I think this whole issue has been a case of barking up the wrong tree.

GOTO as such doesn't seem problematic to me, but rather it's very often a symptom of an actual sin: spaghetti code.

If the GOTO causes major crossing of flow control lines then it's bad, period.  If it crosses no flow control lines it's harmless.  In the grey zone in between we have things like loop bailouts, there are still some languages that haven't added constructs that cover all the legit grey cases.

The only case I've found myself actually using it in many years is the case of the loop where the decision point is in the middle of the loop.  You're left with either duplicated code, a flag or a GOTO.  I find the GOTO solution the best of the three.  There is no crossing of flow control lines here, it's harmless.

Title: Is using goto ever worthwhile?


问:
Source/Version control for application used by multiple companies
Do you find it easier to keep a branch for each company that uses software you support/develop? Each company will want "customizations" and I am just trying to figure out the best way to handle those changes. A branch for each company makes sense in the short term but I could see how this could cause issues with upgrades when a new version is developed.

Is better to have a branch for each company or to setup customizations so that they are always merged to a main branch to minimize issues with future releases?

答:
While S.Robins is correct when he says this is a design and distribution problem not a version control problem, we have to be pragmatic. If you can't redesign your product (to use dependency injection for configuration for instance) then you might still be able to use your VCS to assist in managing the complexity your design introduces.

The big problem with using branches to maintain different versions of a product for different customers is managing the scope and side effects of merges.

If you only ever develop new features outside of the customer specific branch, and only ever make customer specific changes in the customer branch then you will be fine. New features can be pulled down from the feature branch and customer changes never need to be merged up.

The problems come when you try to add a new feature in a customer branch or fix a bug there and then pull those changes out of the customer branch. Then you have to be very careful not to pull customer specific changes along with them.

Having worked in such an environment before, and experienced the pain of untangling an ill-advised merge, I would now work in a different way if I needed to support this kind of environment again.

I would put all customer specific modifications into a patch queue, managed in a per customer repository separate from the main code repository (or repositories).

With Mercurial, I would suggest you look at Mercurial Queues, an extension which comes as standard with TortoiseHg (you just have to enable it). With git, then this answer to git equivalent to hg mq? has some excellent pointers for equivalent git functionality.


问:
How does one effectively implement the 80/20 rule for developer time?
I am a developer at a bank where an 80/20 rule is implemented. 80% of the time you work on your assigned project and 20% you work on something that interests you. However, I'm not really sure how to do that. I'm hoping there are others out there who can provide me with advice on how to.

My problem is that when I really get 'in the zone', all I can think about is the task at hand. If this is a 20%'er, the last thing I want to do is stop and go, lose momentum and go back to work on my main project.

Am I suppose to work 4 days on something and 1 day on something else? or 4 weeks and 1 week?

I know this depends on the company, but I'm hoping to get a feel for how this is done industry wide.

答:
The way I see it you have a two options as long as you have a legitimate company policy that allows you your 20%. Make sure that you get your plan approved by your manager.

Block out 2 hours of each 8 hour day on your calendar for research time

Spend one day a week on research and the other four focusing on your main project

As far as what you are going to research/learn take the time to create a learning plan and set goals.  Talk to your manager and see if he/she has any suggestions on things to focus on.  Then use Doc Browns suggestion to break your study time into regular tasks.  Think about blogging what you are learning.

Whatever you choose to do make sure that you have a plan and document what you are doing so that you can show your employer.  Sitting and surfing the web and reading random articles is great and you can learn a lot doing it but you will have nothing to show for it.  Tracking the articles you are reading helps with that.


答:
Use a white board. Put tasks on their. When you start on one task take it from the column "waiting" to "in progress" column and write down the datetime on it. When you have to switch on another task, put it back to the "waiting" column (write down date/time).

Don't trust software or virtual systems, they are unreliable ;)

Title: Hard-copy approaches to time tracking


答:
It's entirely subjective, but here's my basic rules for my usage.

1) Is my house on fire? Obviously, not literally, but is this a problem that needs not just an immediate solution, but an emergency solution. If so, take a crack at it, fail quickly, get the best help possible.

2) Is this something that I can research? If it's something where I've got the time and it's researchable I'll go down that route, and that includes SO as a complimentary resource. SO is great, so is Wiki, so are the other dozens of resources.
Read lots, it helps your understanding when there's different approaches to an issue, but first spend the time trying to see if your existing knowledge can be reapplied to the issue, then you've built yourself a new mental tool.

3) Is this something that falls outside my skill-set/is so obscure that there's probably 100 people who've ever seen it? This happens, and happens often. I'll generally try research for an hour or two then head here or other resources.

I know it's more noble to sit and do the research and spend the time, but often we have time constraints and you use every resource available, even if it feels like 'cheating' the system.


问:
Why should identifiers not begin with a number?
Most programming languages appear to be designed to not allow one to declare an identifier that starts with a number. I was just curious to know the reason. I have already searched the web, but couldn't find a satisfactory explanation.</p>

答:
Fortran had a huge effect on how later languages were designed. Early on (some of these problems have since been fixed) Fortran had almost no rules restricting what name you could give to an identifier. This made the language extremely difficult to parse both for compilers and for programmers. Here's one classic example:

```<code>if if .eq. then then = else else else = endif endif
K  I   K   K    I      I    K    I      I     K
</code>```

Here I've marked the "language key words" with K and the identifiers (variable names) I. Given that there's no difference in spelling, I think you can probably understand how confusing this could be. Of course, this is an extreme example, and it's unlikely anybody ever wrote code quite like this on purpose. Sometimes people did "recycle" language key words as identifier names though -- and in a lot of cases a simple typo could result in code that the language spec said should be parsed this way, even though it wasn't intended at all. For another well-known example, compare this:

```<code>do 10 i = 1,10
</code>```

to this:

```<code>do 10 i = 1.10
</code>```

The first is a do loop -- iterating a block of code 10 times. The second, however, has had the comma changed to a decimal point, so it's assigning the value 1.10 to a variable named do 10 i.

This also meant that writing a Fortran parser was relatively difficult -- you couldn't be certain that the do at the beginning of the line was really a key word until you reached the end of the line, and verified that all the other elements of a do loop were present. The parser generally had to be ready to "backtrack", re-parsing the line from the beginning to come to the "correct" (but often unintended) answer of what was really there.

After a few years of this, language designers (most of them anyway) went toward the opposite extreme -- restricting nearly everything about the language as much as possible without the users complaining too much.

Early BASIC, for example, basically said you couldn't even use a key word as part of an identifier -- for example, fora=1 would be parsed as for a = 1 (i.e., the beginning of a for loop, not an assignment). That apparently generated enough complaints that it didn't last very long. The rule about starting an identifier with a digit apparently hasn't generated a lot of complaints, so it continues to be used (at least in most languages).

Body:
Fortran had a huge effect on how later languages were designed. Early on (some of these problems have since been fixed) Fortran had almost no rules restricting what name you could give to an identifier. This made the language extremely difficult to parse both for compilers and for programmers. Here's one classic example:

if if .eq. then then = else else else = endif endif
K  I   K   K    I      I    K    I      I     K

Here I've marked the "language key words" with K and the identifiers (variable names) I. Given that there's no difference in spelling, I think you can probably understand how confusing this could be. Of course, this is an extreme example, and it's unlikely anybody ever wrote code quite like this on purpose. Sometimes people did "recycle" language key words as identifier names though -- and in a lot of cases a simple typo could result in code that the language spec said should be parsed this way, even though it wasn't intended at all. For another well-known example, compare this:

do 10 i = 1,10

to this:

do 10 i = 1.10

The first is a do loop -- iterating a block of code 10 times. The second, however, has had the comma changed to a decimal point, so it's assigning the value 1.10 to a variable named do 10 i.

This also meant that writing a Fortran parser was relatively difficult -- you couldn't be certain that the do at the beginning of the line was really a key word until you reached the end of the line, and verified that all the other elements of a do loop were present. The parser generally had to be ready to "backtrack", re-parsing the line from the beginning to come to the "correct" (but often unintended) answer of what was really there.

After a few years of this, language designers (most of them anyway) went toward the opposite extreme -- restricting nearly everything about the language as much as possible without the users complaining too much.

Early BASIC, for example, basically said you couldn't even use a key word as part of an identifier -- for example, fora=1 would be parsed as for a = 1 (i.e., the beginning of a for loop, not an assignment). That apparently generated enough complaints that it didn't last very long. The rule about starting an identifier with a digit apparently hasn't generated a lot of complaints, so it continues to be used (at least in most languages).


答:
There are many practical uses for a service. One main practical use is the interaction between UI and service (or daemon in unix) programs, which is, in this case, the difference between a client and a server. A server receives requests, processes the request, and usually sends back a reply. In other words, it SERVES a request. Think about SQLSERVER, IIS, or telnet. A client, usually utilizes a server by sending requests to the server and then displaying or processing the reply. i.e. A data entry application, a web application ... The server is almost always installed as a service in windows (or a daemon in unix) and the client is usually just a normal app with a gui. There are many more complex uses of a service, but this is the one you will probably use the most.

For example: I am currently working on a SIP/H323 video server. It receives requests from an application using an SDK that I wrote, processes them, and replies back. The video server application is installed as a daemon on an embeded linux machine (it would be a service on an embeded Windows machine, but who uses Windows for embeded anyways) and any application utilizing the SDK would be considered a client.

Of course, you could write such applications and not make them a service. You could still make them start upon starting Windows and have them run in the background. However, it involves several registry entries and some finagling in your code--it is much easier to do using the c api than in something like .NET. Microsoft has on the other hand, made this much easier by creating services and allowing us to register them with the O.S. It is much simpler and easier to implement than doing it manually.

Title: What are the practical uses of Windows Services?

Body:
I am new to working with Windows Services. Although I have learnt to create  Windows Services in VS2010  I would like to know some practical ways in which windows services could be used?

I tried Googling with the current context in mind only to find more tutorials on how to create Windows Services.

EDIT on Bounty Offer:

All the answers are great but I was looking for more practical examples on windows services and their implications? This will help developers know when it is appropriate to use them with the case study.


问:
How to prevent corrupting an hierarchical XML tree?
We have an XML tree which stores the relationship between folders and video files. So each folder could be the artists name and below it we have the videos of the artist. Also each folder can have other sub folders.

This tree structure can be accessed by multiple users where some users could be deleting videos, others moving videos between folders and others possibly renaming folders.

What I need is a mechanism where I lock parts of the tree when one user is working on it and when multiple users all work on their parts of the tree, when they make their changes, the tree is not corrupted. Is this possible to implement when using XML?

答:
You will need control over all of the code that is accessing the XML. There is nothing inherently built into XML that XML editors, text editors and other programs will respect as a locking feature.

If you control the code, there are a number of ways to go.  The easiest way is probably to add a "LockedBy" attribute to the XML node you want to lock.


答:
Jarrod Nettles's answer is good.  I would add this:

Expect that at least one of the other three people will be completely useless.

Just accept that you will feel like you are doing most (or all) of the work, but everyone will get equal credit.  Any attempt at trying to make things "fair" will only cause unnecessary conflict and slow you down.

Stay in contact with any team members who are good.  Such people are hard to find, and you will want to work with them again.


答:
If you are designing a Windows desktop application that needs to run as standard user but sometimes needs to perform a task that requires admin privileges you can use a service.

Your installer installs the service with the needed permissions, your desktop application calls in to the service when it needs to perform a task with admin privilege.

There are security implications to this approach that are beyond the scope of this answer.


问:
Can web technologies, like PHP, HTML, and CSS, be used for desktop development?
I have to develop an application for a gas agency where a database will store consumer numbers, names, addresses, and date delivered for a town with nearly 20,000 people. I only know PHP, MySQL, CSS, jQuery, and other web based technologies. Is it possible to deliver a package to the client using these technologies that can be installed on a computer and used locally?

This application will run on a single PC for a single user. I'm familiar with tools such as XAMPP, but I do not want to run a web server locally. Both the application and database will be securely running on a particular computer. In the future, if this application must be on multiple computers, I want the database and application to be portable.

I have searched for similar questions on Stack Overflow and I did find some recommendations like Jetty, Adobe Air and the recent Web SQL database. Is PHP GTK also a viable tool for building professional applications?

I would like a recommendation specific for this kind of app.

答:
EDIT.
There is a binary release of PHP Desktop with Internet Explorer engine ready, go download it at:

http://code.google.com/p/phpdesktop/

(read "SUMMARY" for a newbie explanation)

In short:

Host a WebBrowser control in a simple c++ app.

Call ShellExecute() to run php 5.4.0 builtin webserver.

Use sqlite as your database.

In details:

Create a simple win32 application that hosts WebBrowser control, for example with C++ and MFC:

http://msdn.microsoft.com/en-us/library/ie/aa752046(v=vs.85).aspx

This can all be done using simple wizards, you don't need to know C++ or anything, but you have to install VisualStudio, then run the wizard and change the path that is on this line:

m_browser.Navigate("127.0.0.1:1234", NULL, NULL, NULL, NULL);

(that navigate call should really happen after step 2. - when you have php server running)

You need to add another line in your c++ program, a call to ShellExecute() that will start the php 5.4.0 builtin server.

ShellExecute() docs at MSDN:

http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx

PHP 5.4 builtin webserver:

http://php.net/manual/en/features.commandline.webserver.php

That line will look something like this:

ShellExecute(NULL, TEXT("open"), TEXT("C:\program files\YourApplication\php.exe"), "-S 127.0.0.1:1234", NULL, SW_HIDE);

(you will have to close that webserver when your application is being closed)

SQLite is a simple database and don't need to run any additional service, a php builtin server that is explained in step 2 is all that is required to connect to sqlite database. In php.ini you need to load PDO extension + pdo_sqlite.

Put your exe (YourProgram.exe) + php binaries (php.exe + dlls + extensions + php.ini) + your .php source files => put it all into one directory, create some installer using for example NSIS:

http://nsis.sourceforge.net/Main_Page

and you're ready to rock.

GooD LucK.

PS.
Regarding the PHP-GTK, have a look at this interesting project I've came across recently, WinBinder: http://winbinder.org/index.php

SUMMARY

You create a c++ wrapper only once and it's easy, then you can run your php scripts as a native windows application - a IE webbrowser control is created inside your application's window and it navigates to 127.0.0.1:1234, which is the output of your php scripts. It looks like a regular program, but it's really an embedded browser inside your application.

There is no installation of apache, php or mysql required - it's like running native windows application. A small c++ wrapper that can be easily created with simple wizards and that can run your PHP scripts later on clients machines, with no hassle, with a feeling of a normal desktop application:)

There is no need to install anything, as it uses PHP 5.4 which comes with a builtin web-server, it can be started easily with 1 line using c++ call to ShellExecute(). For database you can use SQLite which does not require running any service, php alone is sufficient.

Hope it is clear right now.


答:
I think the key here isn't to focus on the 80% / 20% as much as focus on making sure you are learning and pushing yourself with new technologies. If you do this already with the stuff you work on daily, great! If not, then make sure to either mix in new stuff or set aside some time right after you complete a deliverable and do it then.

I realize some new technologies don't lend themselves to stable development (CTPs, Beta, etc.) and I'm not advocating that you mix that stuff into your normal work. Unless that's the type of edge your company rides.

Title: How does one effectively implement the 80/20 rule for developer time?

Body:
I am a developer at a bank where an 80/20 rule is implemented. 80% of the time you work on your assigned project and 20% you work on something that interests you. However, I'm not really sure how to do that. I'm hoping there are others out there who can provide me with advice on how to.

My problem is that when I really get 'in the zone', all I can think about is the task at hand. If this is a 20%'er, the last thing I want to do is stop and go, lose momentum and go back to work on my main project.

Am I suppose to work 4 days on something and 1 day on something else? or 4 weeks and 1 week?

I know this depends on the company, but I'm hoping to get a feel for how this is done industry wide.