答:
As links can get broken or otherwise invalidated, you should not depend on them for your documentation.

If you write something non-obvious based on an answer on StackOverflow or based on some other content on the internet, then you should include enough information in your documentation about what the code does and why it is written that way that future maintainers do not need to follow the links, but can understand the code from the documentation alone.

You can always include the link as a place where more information can be obtained. It can also be useful if you want to check later if the advise that was given at the time is still considered the best advise today.

Title: Referencing StackOverflow questions in comments

Body:
Often when coding I'll get stuck on a particularly tricky problem and will go about searching for a solution. More often than not this leads me to a StackOverflow question that provides a full or partial solution, often with code than can be used directly by pasting into the original code.

In some cases this can lead to code that looks unintuitive or does some seemingly unusual things - such as overloading existing methods in classes, reimplementing in-built functions with the same name or otherwise breaking some aspect of "good practise" to achieve a solution. Sometimes these look like bad practise, but due to problems in the code

In cases like these I often find myself including a link to the answer that I've implemented, with some brief explanation rather than rewriting or duplicating verbose explanations.

Is including URLs to solutions for these kinds of problems in comments a common practise, or is there a better way to document this kind of code?

As an example of this kind of issue, I recently asked a question about resolving a conflict with the Python property decorator, where the solution was to rename the Python in-built function and included a link to the question in the code.


问:
Google Summer of Code Experience
I was a Google Summer of Code student this year and successfully completed my project. It was an awesome learning experience.

Just wondering, from an industry point of view - how is or how well is a Summer of Code experience viewed? I mean, if you were going to hire me, would it mean anything to you? I am just asking this since doing SoC != an internship. As a SoC student, I was a independent contractor for Google. Sure, there was proper development, but I am interested in looking at it from the experience you guys have here. Would you prefer me?

Sorry for not revealing my name; I'd hope you understand.

答: I think this is a great reference and if I was to hire someone, I would prefer a SoC student over someone who had an internship, all other qualities being equivalent.</p>

ContentLicense: CC BY-SA 2.5

Title: Google Summer of Code Experience


问:
Accurate calculation of a raster image's boundary length
I have a rasterized image that contains two colors: white and black.  The black portion is entirely connected and looks like a big blob.  Is there a good way to estimate the length of the boundary between the regions?

One method I have considered is to simply count how many "edges" of the rasterized grid have a different color on each side.  However, for e.g. a purely diagonal line, this will overestimate the distance of the boundary by a factor of sqrt(2).  Is there a better method for estimating the boundary length which does not have this problem?

答:
The blog post "Measuring boundary length" by Cris Luengo discusses precisely this problem and describes several solutions of increasing sophistication. In case the blog goes down, here is a permanent reference to the best one discussed in the post:

Vossepoel and Smeulders, "Vector code probability and metrication error in the representation of straight lines of finite length" (Computer Graphics and Image Processing 20(4):347-364, 1982).

ContentLicense: CC BY-SA 3.0


问:
How should I remember what I was doing and why on a project three months back?
I was working on a project three months back, and then suddenly another urgent project appeared and I was asked to shift my attention.

Starting tomorrow, I'll be heading back to the old project. I realize that I do not remember what exactly I was doing. I don't know where to begin.

How can I document a project such that anytime I look back it shouldn't take me more than a few minutes to get going from wherever I left. Are there best practices?

答:
There's a lot of long answers. This is a short one about what helps me the most:

Clean code.

Clean code.

Clean code.

Version control (diffs and commit comments).

A Post-It note or a Todo-List or a Kanban-Board (see e.g. Trello and Evernote)

However, Diffs, Commit comments, Post-It notes, Todo-Lists or Kanban-Board can be misinterpreted over time for the lack of context.
So here's the one thing that is most important:

CLEAN CODE.


问:
What is design pattern/paradigm for ASP.NET web-apps?
I don't actually know if my question is correct, but working on a webapp porting from ASP.NET world to Java + Spring platform I came up with this question in mind.

Using Spring MVC, the new version of the the application, I'm obviously applying MVC pattern, but which was the ASP.NET design/paradigm.

I know that ASP.NET uses event-oriented paradigm, but is this a design pattern? Hope to be clear...

答:
I don't think Asp.Net is really based on a Design Pattern. It's just a Framework developed with a similar concept to the Windows Forms.

If you want to use a pattern to develop a Web Site with .Net Framework, I suggest to have a look to Asp.Mvc. It's another technology from Microsoft based on the MVC pattern.

At first point, I have partially misunderstood the question. If you are trying to understand the pattern eventually behind Asp.Net to convert it into a MVC pattern, well, there is no pattern as I said before.

Asp.Net it is  totally based on the postback concept. Basically, every time an event (like a click on a button) is fired, the Asp.Net engine execute a post request to the same page, so it can call the method attached to the event.

So, if you want to convert the old project using an MVC pattern, I think you will spend most of your time converting the events into manual post requests.

Anyway, when you are facing a conversion from a technology to another it's better to understand what happens behind the scenes, instead just converting literally the old code into the new one.


问:
Multiple many to many relations or one option table?
Let's say I have a database of persons who have some properties. For the sake of this problem let's say all of these properties relate as N-N.

I can either create two tables for each property (one for different values and one for cross-referencing them to the main object).

Or, I can make the following structure:

Basically having just one huge table of values.

Are there any advantages to this approach? Also, does this approach or pattern have a name that I can look up?

UPDATE:
For example, we make classifier pets with properties cat, dog and fish. So one person may have a cat and a dog (or one pet, or none). And we make a classifier hobby with values skiing, skating, football and TV. So Joe has properties cat, dog, and TV. Then cat and dog are pets and TV is hobby.

The question is, is it worthwhile to put this data using this diagram, or is it a better idea to just create pets, pets_xref, hobby, hobby_xref tables?

答:
I have to follow Igby, this design you tend to do, is not very suggested. If you ever worked with OR mapper you can understand the problem even further.

Because on your design you would have "multiple entities" (in the mind context) behind "one n:n relationship".
Rather do the work and build up a new table, relation table and the relation for every "property" (like you call it) of any entity.

You cannot integrate 1:n in your design either. Then you would create new tables for 1:n and none for n:n on the person entity, that is dirty.


问:
Why is polling accepted in web programming?
I am currently working on a Ruby on Rails project which shows a list of images.

A must-have for this project is that it shows new posts in realtime without the need of refreshing the web page. After searching for a while, I've stumbled upon some JavaScript solutions and services such as PubNub; however, none of the provided solutions made sense at all.

In the JavaScript solution (polling) the following happens:

User 1 views the list of photos.

In the background the JavaScript code is polling an endpoint every second to see if there is a new post.

User 2 adds a new photo.

There is a delay of 50 ms before the new cycle is triggered and fetches the new data.

The new content is loaded in the DOM.

This seems odd when translated to a real world example:

User 1 holds a pile of pictures on his/her desk.

He/she walks to the photographer every second and asks if he has a new one.

The photographer makes a new photo.

This second when he/she walks in, she can take the picture and put it on the pile.

In my opinion the solution should be as following:

User 1 holds a pile of pictures on his/her desk.

The photographer takes a new picture.

The photographer walks to the pile and puts it with the rest.

The PubNub solution is basically the same, however this time there is an intern walking between the parties to share the data.

Needless to say, both solutions are very energy consuming as they are triggered even when there is no data to load.

As far as my knowledge goes there is no (logic) explanation why this way of implementation is used in almost every realtime application.

答:
Why is polling accepted? Because in reality every solution is actually low-level polling!

If the server should update you as soon as new pictures are available, it usually has to have a connection to you - because IP addresses change often and you never know if someone isn't interested anymore, so the client has to send some form of keep-alive signal, for example, "I'm still here, I'm not offline"

All stateful connections (for example, TCP/IP) work the same, since you can only send singular data-packets over the Internet; you never know if the other party is still there.

So every protocol has a timeout. If an entity doesn't answer within X seconds, it is presumed to be dead. So even if you have only an open connection between server and client, without sending any data, the server and client have to send regular keep-alive packets (this is handled low-level if you open a connection between them) - and how is this in the end any different from polling?

So the best approach would probably be longpolling:

The client sends a request immediately after loading the site (for example, telling the photographer "Tell me if there are any new pictures"), but the server doesn't answer if there aren't any new pictures. As soon as the request times out, the client asks again.

If the server now has any new pictures, it can immediately answer all the clients which stand in line for new pictures. So your reaction time after a new picture is even shorter than with push, since the client is still waiting in an open connection for a reply and you don't have to build up a connection to the client. And the polling requests from the client are not much more traffic than a constant connection between client and server for an answer!


问:
Object Design & Cohesion - Issue & potential refactoring
Abstract

I have been trying to get my head around the cohesiveness of some functionality in our code base.  I’ve approached this design in different ways, and lately I’m convinced that I took the wrong approach, as in I incorrectly applied the Single Responsibility Principle.

Issue

The problem domain is a Well, otherwise known as a round hole in the ground.  The current code looks something like this...  I have a set of data in a data only object...

Note: This is not the full code, just method names to keep things short...

```<code>public class WellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }
}
</code>```

I broke functionality that operates on this data into several small classes. As per below…

```<code>public class ReferenceWellSurvey
{
   ICollection<SurveyPointCalculate> _calculatedSurveyPoints;
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
}

public class ReferenceWellGeometry
{
   ICollection<GeometryItem> _geometryItems;
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
}

public class ReferenceWellTemperature
{
   ICollection<TemperaturePoint> _wellTemperatures;
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
Etc.
</code>```

I’ve realized lately when looking at our code that I have to glue all this back together to make it usable where I need it in the application logic.  Something like….

```<code>public class ReferenceWellData
{
private IReferenceWellGeometry _refWellGeometry;
private IReferenceWellTemperature _refWellGeometry;
          private IReferenceWell _refWellGeometry;
          private IReferenceFluid _refWellFluid;
       //Proxy functions from each class to glue it all back together…
}
</code>```

A few things that led me to the current mess. The well data class contains several collections of information and if everything is in one class most functions will only operate on a small subset of the data.  At the time I felt that would create low cohesion, now a few months later, I feel these things do actually all belong together.  Additionally, there are several classes in my code that need to call just one method of the ReferenceWellSurvey class, GetTvdAtDepth().  Really what I did didn’t solve this issue.

After thinking more about this, and after reading this Wikipedia article http://en.wikipedia.org/wiki/Cohesion_(computer_science), I’m starting to see that I have committed a few programming sins.

•   Anemic domain model

•   Low cohesion

•   Constructor over injection in code where I try to glue things together

•   Giving a class that depends on GetTvdAtDepth access to other methods that it does not need, violated Interface Segregation Principle.

Solution

I’m looking for that Goldilox design that doesn’t give too much responsibility to any one class (No God Objects), while yet maintaining a good degree of cohesion.

My current thoughts on fixing this are as follows.  Move the functionality that operates on the well data into the same class.  This should help get this functionality closer to Communicational/informational cohesion.

```<code>public class WellData : IWellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }

   // Operates on SurveyPoint collection
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
   //Operates on WellGeometry collection
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
   //Operates on WellTemperature collection
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
</code>```

Next to address the issue of several classes needing just one function, I could make this one function into a separate interface IGetTvdAtDepth.  In this way, my classes that need that functionality can depend just on this interface, which I can inherit into my WellData interface, and implement it there, but not tie my other classes to all the functionality that is in my WellData class.

Thoughts on this approach vs. the original approach?  One thing that bothers me about doing things way is that in my API I'm using bastard injection to fulfill the required dependencies of this class... Right now I have three required dependencies, a Survey calculator, and a special class that references data at different measured depths. I'd like to move away from this, but that seems to point back toward having services do more of the lifting...

答:
If you didn't need ReferenceWellSurvey, ReferenceWellGeometry, etc... to communicate then it made sense (from an implementation point of view) to do this break-down.
However it is not advisable to rely on implementation level details to establish your class structure.

"I’ve realized lately when looking at our code that I have to glue all this back together to make it usable where I need it in the application logic."
You mean, because the user of this class doesn't care ( and so, would better not be exposed to ) about the implementation level decomposition?
But glueing things in this way isn't necessarily bad.

"A few things that led me to the current mess"...
What current mess? The fact that a collection of classes, each in charge of a small set of related data, support the implementation of another class, doesn't constitute a mess. Now, if you need to import ReferenceWellSurvey from ReferenceWellGeometry (or any similar dependencies between these supportive classes), well that would be a mess and would undermine your 'implementation oriented' breakdown.

WellData should live on (is there a reason not to name this 'Well'? Are there concurrent models of a well in your data) whether you keep the service oriented breakdown or not. A well designed class is a class that's intuitively named and exposes useful functionality.

IWellData may live on. Assuming anything is using it.

If your breakdown into service oriented classes already started feeling awkward, get rid of it. Try to look at this from the point of a newbie trying to maintain your code. A poor old Well object will be a delight for them.

IGetTvdAtDepth (rename to ITvdCalculator? Is Tvd an acronym?) looks okay, just make sure that hiding remaining functionality is legitimate (if somebody wanted to access another Well method in the future, would be fine? In other words, are you hiding these methods because they are not needed, or because they should not be accessed?)

"One thing that bothers me about doing things way is that in my API I'm using bastard injection to fulfill the required dependencies of this class... Right now I have three required dependencies"
Is this a problem? If so, that might provide the rationale for defining IWellData.

In conclusion I think your proposed solution may be fine. Would this go against the responsibility principle? Maybe, but I think a design that endorses the definition of 'Well' in your domain is a better design than creating implementation level classes.


问:
Android SDK and Iphone SDK limitations
I have an idea that would require triggering a call or text message simply by pressing or dialing a certain number.

Example: Pressing 2324 on the pin code. Despite it not being your pin code to unlock the device, my application (always running in the back) would detect your code "2324" has been typed in and send a call or text message.

Another Example: Holding volume button for 5 seconds and then pressing "2" on pin code lock. This could be another trigger.

My question is, how flexible are the iOS and Android SDK's to allow this level of customization? Can I override tone settings via an application (change from Silent to Normal)? Can I close applications? What can't I do?

I tried researching this but have not come up with any recent or updated answer. Hoping someone could clarify what I can't/can do with Iphone and Android SDK's.

答:
Android:

Pretty sure its not possible to hook into the standard unlock screen in this way.

But, in Android you can write an app to provide a custom lock screen, and once you've done that adding a "duress/distress" function would be easy. If you just search for "Android custom lock screen" you'll find tons.

Edit: or you can write a widget that the user can place on their lock screen, and then capture an interaction in that.

Title: Android SDK and Iphone SDK limitations


问:
Which algorithm is faster?
I'm creating a small game, where the computer generate pseudo random number in give range, and the user have to guess it. I also made the option to play computer vs computer. I mean the computer generate random number and the computer should guess it.

The easiest way I found was to create for loop and increase a variable by 1 until it guesses it.  But I decided to try to create my own algorithm about this.

Basically the variable that holds the guess number is equal to range / 2, and then the program enters into the while loop where if the random number > the number which is generated by logic(the one which is = to range /2) then 2 it to two and add 1 to it. If the number is < the program * by 2 and add one to it until it guess the number.

Here is code in C++:

```<code>void aiVsAI(int range){ // range argument is used to be given to the randome generator func
    int random_number = generate_random_number(range); // assigning the random number to variable
    int guess = range / 2; // the computer guess number
    int tries = 0; // how many tries the computer needed to guess the number
    while(guess != random_number){ // while the guess isn't equel to the random number
        if(guess > random_number){ // if the guess is > than the random number
            guess = guess / 2 + 1; // dev it to 2 and add one to it
        }
        else if(guess < random_number){ // if the number is < than the number then
            guess = guess * 2 + 1; // * it with 2 and add one
        }
        tries++; // increase the number of tires
    }
    std::cout << tries;
}
</code>```

the generate_random_number is function that will generate pseudo-random number.

My question is which algorithm is faster this one or just using for loop and increasing variable with one until it guess the number?

Here is the full code if anyone need it for something:

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <time.h>

//function that will generate random number
int generate_random_number(int range){  // the range argument is used to represent the maximum value of the number
    if(range < 10){ // the range couln't be < 10 but can be ==
        std::cout << "range can't be less than 10";
        exit(1);
    }
    std::srand(time(NULL)); // making sure that the random number will be different every time
    return rand() % range; // returning the random generated number in the specific range
}

//Game computer vs computer
void aiVsAI(int range){ // range argument is used to be given to the randome generator func
    int random_number = generate_random_number(range); // assigning the random number to variable
    int guess = range / 2; // the computer guess number
    int tries = 0; // how many tries the computer needed to guess the number
    while(guess != random_number){ // while the guess isn't equel to the random number
        if(guess > random_number){ // if the guess is > than the random number
            guess = guess / 2 + 1; // dev it to 2 and add one to it
        }
        else if(guess < random_number){ // if the number is < than the number then
            guess = guess * 2 + 1; // * it with 2 and add one
        }
        tries++; // increase the number of tires
    }
    std::cout << tries;
}

// Game human vs human
void humanVsAI(int range){ // range argument is given to the generate random function
    int random_number = generate_random_number(range); // assigning the random number to variable
    int input = 0; // this var represents the user input
    int tries = 0; // the number of tries user had make to guess the number
    while(input != random_number){
        std::cout << "Enter number: "; // alerting the user to enter a number
        std::cin >> input; // getting the number
        if(input < random_number) // checking if the input > than the random num
            std::cout << "You didn't guess it,you are too low..., try again!\n"; // alerting the user
        else{ // else it will be > than the number
            std::cout << "You didn't guess it,you are too high..., try again!\n"; // alerting the user
        }
        tries++; // increasing tries by one for each try//
    }
    std::cout << "\n\nYou guess it! You need " << tries << " to do this.\n\n";
}

//game Human vs Human
void humanVsHuman(int range){
    int number_to_guess; // the number which must be guessed
    int user_guess; // user input
    int guess;
    std::cout << "Enter number int range 1- "<< range<<": \n"; // alerting the user to enter number
    std::cin >> number_to_guess; // entering number
    for(int i = 0; i < 100;i++){ //Clearing the screen
        std::cout << "\n";
    }
    while(user_guess != number_to_guess){
        guess++;
        std::cout << "Please enter numer:\n"; // alerting the user
        std::cin >> user_guess; // Getting the user input
        if(user_guess < number_to_guess)
            std::cout << "You didn't guess it,you are too low..., try again!\n";
        else if(user_guess > number_to_guess)
            std::cout << "You didn't guess it,you are too high..., try again!\n";
    }
    std::cout << "You guess the number\n";
}
int main(){
    std::string game_type;
    char play_game;
    int range = 0;
    while(1){
        std::cout << "Please enter range(type 100 to leave it as default)\n";
        std::cin >> range;
        std::cout <<"What you want to play AI vs human, human vs human or AI vs AI ?\n";
        std::cin.ignore(); // for get line
        std::getline(std::cin, game_type); // getting the user input
        std::cin.clear(); // clearing
        if(game_type == "AI vs AI" || game_type == "ai vs ai"){ // if the user chose AI vs AI
            std::cout<<"You choosed AI vs AI\n";
            aiVsAI(range); // calling the AI function
        }
        else if(game_type == "human vs ai"
                || game_type  == "ai vs human"
                || game_type == "human vs AI"
                || game_type == "Human vs AI"
                || game_type == "Human vs ai"
                ){ // if the user chossed AI vs human
            std::cout << "You choosed human vs AI\n";
            humanVsAI(range); // calling the human vs human function
        }
        else if(game_type == "human vs human"
                ||game_type == "Human vs Human"
                ||game_type == "Human vs human"
                ||game_type == "human vs Human"){ // if the user choosed human vs human
            std::cout <<"You choose human vs human\n";
            humanVsHuman(range); // calling the human vs human function
        }
        else{ // In case of any error
            std::cerr << "An error occured!";
        }
        std::cout << "Do you want to play another game?\n"; // do you want another game????
        std::cin >> play_game;
        if(play_game == 'y' || play_game == 'Y')
           std::cout <<" starting another game\n";
        else
            break;  // enough playing for now.
    }
    return 0;

}
</code>```

答: The more sophisticated algorithm is definitely more efficient: it requires logarithmic time vs. linear time to find the value. Here is a description of binary search; that's basically what you have reinvented.</p>

Title: Which algorithm is faster?


问:
External libraries licensing
The problem I have might seem trivial for some of you but in general I have a question about all those "free" software licenses (mainly for PHP libraries).

Let's assume that I want to create project for end-user and I want to sell it to them and if possible encrypt my source code.

For example for Zend Framework licence is New BSD License and for Laravel it's MIT license. On Zend framework there is such short info:

Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

but it means nothing for me. What does it mean the first one? Should I simple download Zend Framework and put in directory and when I don't do anything with it I can forget about it or maybe I should tell my client that I used framework and my software may not working because

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES ...

I really don't understand how those licenses work and what are differences between those licenses. Could you provide me some help or external resources where this issue is explained in a simple way?

答:
To start with the paragraph in all-caps ("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES ..."), that is called a disclaimer. These kinds of disclaimers are very common for software and their purpose is that if you get hit by a problem that could be caused by software package X, then you can't take the authors of X to court and sue them for damages.

What that BSD license text means (and the MIT license is similar) is that you must not remove the copyright line (Copyright <year>, <names>) or change the license text (which extends to the end of the disclaimer). If you made substantive changes to a source file, then you may add your name to the copyright line and change the year to the current year.

Also, if you distribute your software in binary (compiled) form, then you must have some documentation that states that portions of your software are written by others and which copyright license applies to their code. Having this documentation is also a good idea if you distribute in source code form.

If you use multiple external libraries that fall under the same license, I would recommend to organize the documentation like this:

For each relevant license, create a file named LICENSE.<licence> with the text of the license (minus the Copyright lines!)

In your README (or similar) file, have a section 'External libraries', like this:

External libraries

  ------------------

This software uses the following external libraries:

Zend Framework: Copyright <copyright information for Zend Framework>. Licensed under BSD license, see LICENSES.BSD for details

  Website: <Zend Framework URL>

Laravel: Copyright <copyright information for Laravel>. Licensed under MIT license, see LICENSES.MIT for details

  Website: <Laravel URL>

The BSD and MIT licenses are permissive licenses, because they don't put any further restrictions on how you can use and re-distribute code licensed under them.

Other licenses may put additional restrictions in place. A common one is that you must also provide the source code for modifications that you made. The GPL goes even a step further and requires you to provide source code for any application or library that is used in the same program as a piece of code licensed under the GPL.

Title: External libraries licensing


问:
Filtering common starting/ending characters from array/list of strings
Ok so for example I have an array of strings with each string as below:

364VMS1029
364VMSH920
364VMSH192
364VMSU839
364VMN2382
364VMR223
364VMR2X3
364VMN829
364VMN8757
364VMN831
```

How can I dynamically get the program to recognise the common characters among all strings in the array, which in this case is 364VM and filter them out?
If there's no common character, then don't do anything.

答:
You have to compare every character at the beginning of the strings to see how long the longest common prefix is, and stop once you've found a difference.

(Depending on how expensive string access is vs. sorting, you might save time by first sorting the list and then looking only at the first and last string - whatever they have in common will, by definition, also be common to all strings between them. But it is a matter of profiling to find out whether this saves or adds time.)


问:
Is immutability very worthwhile when there is no concurrency?
It seems that thread-safety is always/often mentioned as the main benefit of using immutable types and especially collections.

I have a situation where I would like to make sure that a method will not modify a dictionary of strings (which are immutable in C#). I’d like to constrain things as much as possible.

However I am not sure whether adding a dependency to a new package (Microsoft Immutable Collections) is worth it. Performance is not a big issue either.

So I guess my question is whether immutable collections are strongly advised for when there are no hard performance requirements and there are no thread safety issues? Consider that value semantics (as in my example) might or might not be a requirement as well.

答:
Immutability simplifies the amount of information you need to track mentally when reading code later. For mutable variables, and especially mutable class members, it's very hard to know what state they will be in at the specific line you're reading about, without running through the code with a debugger. Immutable data is easy to reason about - it will always be the same. If you want to change it, you need to make a new value.

I would honestly prefer making things immutable by default, and then changing them to mutable where it's proven that they need to be, whether this means you need the performance, or an algorithm you have doesn't make sense for immutability.


问:
Roles configuration strategy
We're close to start new project using sf2, and, probably, FosUserBundle.

Keeping that in mind - what's the best strategy to define roles? App will be used by multiple divisions inside our company (every division has it's manager and regular employees), as well as external users, that can be divided into 3 groups (for now).

I'm comming up with two possible solutions:

each role represents specific action in app, i.e.: adding new task action is described as task_new role. Selected users get this role to be able to add new task.

each role represents user ability and every action checks if user has this ability i.e.: when new task is being added, controller checks if current user has role task_access role.

I really somehow like approach to this problem in our current app - there's one place where only admin has access granted, with list of all registered actions. Users are divided into about 10 groups and all you have to do is to check that this group has access to this action. In this case no code-juggling is required, but I'm afraid it will generate some limitations or roles overgrowing in new app.

What I'm really afraid of is spending too much time changing the security code in specific controller/action, I mean, when new user has to get access to specific place, I will have to go to the code, handle new role, code will grow, and so on. I want to keep this time as low as possible, and as flexible as possible.

I believe there are some great solutions to this problem. Am I right?

答:
To avoid having to touch the code when new roles are thought up, I would use a three-way division in my user/role management:

Permissions define actions that are possible. For example, you could have separate permissions for read access, write/modify access, create access, modify permissions, etc. You can even let separate modules define separate permission sets.

Roles represent the set of permissions that groups of similar users will have. For example, Managers, Regular Users, External Users, Administrators

Users have a role (or possibly more) within the system. This is the level at which authentication takes place.

If a new role is thought up that needs a different set of permissions (for example, a Power User), it is just a matter of adding it to the list of roles and assigning the correct set of permissions.

Title: Roles configuration strategy


答:
Your code should express your intention. If you don't want an object to be modified once created, make it impossible to modify.

Immutability has several benefits:

The intention of the original author is expressed better.

How would you be able to know that in the following code, modifying the name would cause the application to generate an exception somewhere later?

```<code>public class Product
{
    public string Name { get; set; }

    ...
}
</code>```

It's easier to make sure that the object wouldn't appear in an invalid state.

You have to control this in a constructor, and only there. On the other hand, if you have a bunch of setters and methods which modify the object, such controls may become particularly difficult, especially when, for example, two fields should change at the same time in order for the object to be valid.

For example, an object is valid if the address is not null or GPS coordinates are not null, but it's invalid if both the address and the GPS coordinates are specified. Can you imagine the hell to validate this if both the address and GPS coordinates have a setter, or both are mutable?

Concurrency.

By the way, in your case, you don't need any third party packages. .NET Framework already includes a ReadOnlyDictionary<TKey, TValue> class.

Title: Is immutability very worthwhile when there is no concurrency?

Body:
It seems that thread-safety is always/often mentioned as the main benefit of using immutable types and especially collections.

I have a situation where I would like to make sure that a method will not modify a dictionary of strings (which are immutable in C#). I’d like to constrain things as much as possible.

However I am not sure whether adding a dependency to a new package (Microsoft Immutable Collections) is worth it. Performance is not a big issue either.

So I guess my question is whether immutable collections are strongly advised for when there are no hard performance requirements and there are no thread safety issues? Consider that value semantics (as in my example) might or might not be a requirement as well.

Body:
Your code should express your intention. If you don't want an object to be modified once created, make it impossible to modify.

Immutability has several benefits:

The intention of the original author is expressed better.

How would you be able to know that in the following code, modifying the name would cause the application to generate an exception somewhere later?

public class Product
{
    public string Name { get; set; }

    ...
}

It's easier to make sure that the object wouldn't appear in an invalid state.

You have to control this in a constructor, and only there. On the other hand, if you have a bunch of setters and methods which modify the object, such controls may become particularly difficult, especially when, for example, two fields should change at the same time in order for the object to be valid.

For example, an object is valid if the address is not null or GPS coordinates are not null, but it's invalid if both the address and the GPS coordinates are specified. Can you imagine the hell to validate this if both the address and GPS coordinates have a setter, or both are mutable?

Concurrency.

By the way, in your case, you don't need any third party packages. .NET Framework already includes a ReadOnlyDictionary<TKey, TValue> class.


问:
Static and dynamic data : should I use different databases?
Say I am building a website that uses two different types of data :

Static : information that will hardly change, like movie awards or world countries names (I want fast access so no external API)

Dynamic : information entered by users

I have not written a single line of code yet. My static db is more likely to be quite large but will not change overtime. As for the dynamic db I have no idea yet but I might need scalability.

Should I use different databases in the long run ? Is it common practice to do so ?

答:
I see no advantages to separating the databases, and several downsides.

You're forced to guess in advance what data will never change and which might change. Such guesses are virtually always wrong in some way.

Additional programming and configuration overhead for dealing with two database connections rather than one.

JOINs between data from the different sources are likely to be much less efficient than they would be in-database.

Two different namespaces for tables mean that you run the danger of name collisions without the system warning you, promoting subtle misunderstandings on the part of the developers (even yourself).


答:
As far as I know, it's not a common practice.

Based on how much your static information is really static you can consider other options to decide where store the data, instead using a database.

For example, if the static data never change you can consider to use a Constants class:

```<code>public static class Constants{

     public const int MyConstantValue = 10;

}
</code>```

The advantage of this technique is to be able to use the intellinse because it's stored in an object.

```<code>var foo = Constants.MyConstantValue;
</code>```

Another option is to use a simple file. For instance, usually with .Net Framework applications you can create an App.Config file where you can store values with a key:

```<code><configuration>
 <appSettings>
    <add key="Setting1" value="Value1" />
    <add key="Setting2" value="Value2" />
 </appSettings>
</configuration>
</code>```

I use for example the App.Config to store the Connection Strings to the external datasources (like the Database connection string).

Generally, it's a good idea to store a static data in the database when you think it's for most of the time a constant information, but you want to able to change it if you need it.

Title: Static and dynamic data : should I use different databases?

Body:
Say I am building a website that uses two different types of data :

Static : information that will hardly change, like movie awards or world countries names (I want fast access so no external API)

Dynamic : information entered by users

I have not written a single line of code yet. My static db is more likely to be quite large but will not change overtime. As for the dynamic db I have no idea yet but I might need scalability.

Should I use different databases in the long run ? Is it common practice to do so ?

Body:
As far as I know, it's not a common practice.

Based on how much your static information is really static you can consider other options to decide where store the data, instead using a database.

For example, if the static data never change you can consider to use a Constants class:

public static class Constants{

     public const int MyConstantValue = 10;

}

The advantage of this technique is to be able to use the intellinse because it's stored in an object.

var foo = Constants.MyConstantValue;

Another option is to use a simple file. For instance, usually with .Net Framework applications you can create an App.Config file where you can store values with a key:

<configuration>
 <appSettings>
    <add key="Setting1" value="Value1" />
    <add key="Setting2" value="Value2" />
 </appSettings>
</configuration>

I use for example the App.Config to store the Connection Strings to the external datasources (like the Database connection string).

Generally, it's a good idea to store a static data in the database when you think it's for most of the time a constant information, but you want to able to change it if you need it.


问:
Passing data between hundreds of objects in java
Currently, I'm working with a group on building a model. This model simulates interactions between many "agents" in a region. Agents can be any entity such as a city, a farmer, a business etc. Each agent is represented by its own object within java. Each agent will need to be able to interact with all of the other agents, and therefore, needs to have access to information about the other agents.

So, for example, lets say we have 1 city object interacting with 99 farmer objects. The city needs to know for instance, the total land that each of the 99 farmers owns in order to perform some sort of calculations.

So, my question is, what is the most performance efficient way of completing something like this? There may even be 500-1000 or more agents in the future, and each agent may need to access many variables from the other agents. Would you potentially set up a table within mysql for each agent and have them access eachother's information that way?
Or can something be set up directly within java that allows the agents to access each other's information.

I'm looking to possibly multithread this model in the future too. In any case, I want the most performance efficient way of completing this.

答:
As pointed out in the other answers, it depends on your unique circumstances (needed to run the simulations) whether to use a real database, or a real geographic information system (GIS).

Regardless of you choice of tooling, one thing is certain: your simulations will involve application logic that is superficially similar to what is done by databases and GIS systems. Namely:

Queries over a large number of objects -
 some of which may be outside the object hierarchy.

Calculations e.g. sums, averages, minimums and maximums, or other statistical / mathematical / geometrical operations over objects within a certain spatial extent.

See: Spatial query, and Nearest neighbor search.

Recognize that you will need to learn new concepts no matter what.

Using existing tools (databases and GIS systems) does not save you from having to learn about relational and spatial queries.

Writing your own code does not save you from having to learn about relational and spatial queries (*).

(*) repeated for emphasis.

However, by using existing tools,

You could save time from implementing algorithms for doing that.

In exchange, you will spend more time learning how those tools work, and formulating your simulation requirements into queries with these tools.

On the other hand, the concern expressed in your question is too far from your immediate needs. Namely:

Should I favor a centralized (database) approach, or a decentralized (peer-to-peer, or object-oriented) approach when modeling these operations?

What would be the performance from each approach?

(See below.)

How do I partition the system for scalability?

You can always revisit architectural decisions next month; however you need to figure out how to meet the needs of your simulation application this week.

What would be the performance from each approach?

Practically speaking, you wouldn't know until you implement both approaches, optimize them, and then compare their performance.

Theoretically speaking, we need to know exactly what types of algorithms (queries) are performed. Such as:

Queries can be solved by "keeping a tally (sum) up to date"

Queries can be solved by a look-up of a handful of items

Queries that involves 2D spatial search

Queries that involves evaluating a mathematical equation for every pair of objects. (This is going to be slow.)

If you only give "examples", the usefulness of the advice will depend on how good your examples reflect your application needs.


问:
How much data should exceptions hold?
Almost all the exceptions I have ever written have been very lightweight, containing a String message and optionally a throwable. In some situations I have included some application specific enum or some other field.

```<code>public class MySpecialException()
{
    private MyErrorCode errorCode;

    public MySpecialException(String message, Throwable cause, MyErrorCode errorCode)
    {
        super(message, cause);
        this.errorCode = errorCode;
    }

    ....
}
</code>```

Now I face a situation where I need to put in 5 or 6 fields in the exception because the error handler that catches them needs them to generate the output.

Would you consider that to be bad code? Can an exception be too big?

```<code>public class MySpecialException()
{
    private String name;
    private int age;
    private int id;
    private int height;
    private String duck;
    private String whatever;

    ....
}
</code>```

答:
Of course it can be too big - virtually everything about coding is a trade-off between different principles, and not wasting memory is one of them.

However, if you need the data in the exception to get the job done, then by definition it's not too big. It would be too big only if there was another mechanism that achieves the same, leads to maintainable code and works like an exception.

But exceptions are first-class language elements that were invented specifically to achieve something that you can't otherwise do (break control flow and transport data somewhere else in the call stack without having to change the intermediate callers), so I doubt that you could find another solution which fulfills that condition.

Title: How much data should exceptions hold?


答:
I think you don't really need all that information. I suppose you need all these values to identify better the cause of failure, so you have different options to achieve this, or at least improve the current solution:

Use a logger. You can log on a file or a database these values before throw the exception

Just store the ID and retrieve manually the entity afterwards, if it's stored in an accessible place like a database

Pass to the exception only the values which are the cause of failures

Anyway, don't store this values inside the exception but just use them to create the exception message in the constructor.

Title: How much data should exceptions hold?

Body:
Almost all the exceptions I have ever written have been very lightweight, containing a String message and optionally a throwable. In some situations I have included some application specific enum or some other field.

```<code>public class MySpecialException()
{
    private MyErrorCode errorCode;

    public MySpecialException(String message, Throwable cause, MyErrorCode errorCode)
    {
        super(message, cause);
        this.errorCode = errorCode;
    }

    ....
}
</code>```

Now I face a situation where I need to put in 5 or 6 fields in the exception because the error handler that catches them needs them to generate the output.

Would you consider that to be bad code? Can an exception be too big?

```<code>public class MySpecialException()
{
    private String name;
    private int age;
    private int id;
    private int height;
    private String duck;
    private String whatever;

    ....
}
</code>```


问:
Which is the more testable C function implementation?
I write code in C. I have been striving to write more testable code but I am a little
confused on deciding between writing pure functions that are really good for testing
but require smaller functions and hurt readability in my opinion and writing functions
that do modify some internal state.

For example (all state variables are declared static and hence are "private" to my module):

Which of this is more testable in your opinion:

```<code>int outer_API_bar()
{
   // Modify internal state
   internal_foo()
}

int internal_foo()
{
  // Do stuff

  if (internal_state_variable)
  {
     // Do some more stuff
     internal_state_variable = false;
  }
}
</code>```

OR

```<code>int outer_API_bar()
{
   // Modify internal state

   internal_foo(internal_state_variable)

   // This could be another function if repeated many
   // times in the module
   if (internal_state_variable)
   {
      internal_state_variable = false;
   }
}

int internal_foo(bool arg)
{
  // Do stuff

  if (arg)
  {
     // Do some more stuff
  }
}
</code>```

Although second implementation is more testable wrt to internal_foo as it has no sideeffects but it makes bar uglier and requires smaller functions that make it hard for the reader to even follow small snippets as he has to constantly shift attention to different functions.

Which one do you think is better ? Compare this to writing OOPS code, the private functions most of the time use internal state and are not pure. Testing is done by setting up internal state on a mock object instance and testing the private function. I am getting a little confused on whether to use or whether to pass in internal state to private functions for the sake of "testability"

答:
The second is better, but

```<code>int internal_foo(bool *arg); // modifies argument
</code>```

keeps it testable while fixing your tiny function tradeoff, and

```<code>bool internal_foo(bool arg); // returns new value
</code>```

is even better if you don't use the existing return value.

Note that in general though, having lots of little functions isn't necessarily a problem. If it makes your code less readable, you might just need to give them better names and/or re-work your logic.

The best and most general solution would be to remove your globals entirely, and have the caller pass an opaque API context into your outer function. This might be overkill in your case though, I can't tell from the code shown.

Body:
The second is better, but

int internal_foo(bool *arg); // modifies argument

keeps it testable while fixing your tiny function tradeoff, and

bool internal_foo(bool arg); // returns new value

is even better if you don't use the existing return value.

Note that in general though, having lots of little functions isn't necessarily a problem. If it makes your code less readable, you might just need to give them better names and/or re-work your logic.

The best and most general solution would be to remove your globals entirely, and have the caller pass an opaque API context into your outer function. This might be overkill in your case though, I can't tell from the code shown.


答:
As long as the guess is consistently high, your algorithm performs well by roughly halving the guess.

Once you have made a low guess, the algorithm severely deteriorates in performance. By doubling after a low guess, you are guaranteed that the next guess will be too high. Now, the +1 factors come into play (especially the one after halving), which let you walk towards the right number at half the speed of a normal loop.

For performance measurements, I would expect the slow walk up to be the dominant factor, making your algorithm slower on average than the simple loop. Given your measurements, either my expectations are wrong, or the distribution of your pseudo-random values happens to be slightly in favor of your algorithm.

If you want a challenge, you could try to implement a binary search. With a range of 100, that algorithm is able to find any number within 10 steps (given that it knows the range).

Title: Which algorithm is faster?

Body:
I'm creating a small game, where the computer generate pseudo random number in give range, and the user have to guess it. I also made the option to play computer vs computer. I mean the computer generate random number and the computer should guess it.

The easiest way I found was to create for loop and increase a variable by 1 until it guesses it.  But I decided to try to create my own algorithm about this.

Basically the variable that holds the guess number is equal to range / 2, and then the program enters into the while loop where if the random number > the number which is generated by logic(the one which is = to range /2) then 2 it to two and add 1 to it. If the number is < the program * by 2 and add one to it until it guess the number.

Here is code in C++:

```<code>void aiVsAI(int range){ // range argument is used to be given to the randome generator func
    int random_number = generate_random_number(range); // assigning the random number to variable
    int guess = range / 2; // the computer guess number
    int tries = 0; // how many tries the computer needed to guess the number
    while(guess != random_number){ // while the guess isn't equel to the random number
        if(guess > random_number){ // if the guess is > than the random number
            guess = guess / 2 + 1; // dev it to 2 and add one to it
        }
        else if(guess < random_number){ // if the number is < than the number then
            guess = guess * 2 + 1; // * it with 2 and add one
        }
        tries++; // increase the number of tires
    }
    std::cout << tries;
}
</code>```

the generate_random_number is function that will generate pseudo-random number.

My question is which algorithm is faster this one or just using for loop and increasing variable with one until it guess the number?

Here is the full code if anyone need it for something:

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <time.h>

//function that will generate random number
int generate_random_number(int range){  // the range argument is used to represent the maximum value of the number
    if(range < 10){ // the range couln't be < 10 but can be ==
        std::cout << "range can't be less than 10";
        exit(1);
    }
    std::srand(time(NULL)); // making sure that the random number will be different every time
    return rand() % range; // returning the random generated number in the specific range
}

//Game computer vs computer
void aiVsAI(int range){ // range argument is used to be given to the randome generator func
    int random_number = generate_random_number(range); // assigning the random number to variable
    int guess = range / 2; // the computer guess number
    int tries = 0; // how many tries the computer needed to guess the number
    while(guess != random_number){ // while the guess isn't equel to the random number
        if(guess > random_number){ // if the guess is > than the random number
            guess = guess / 2 + 1; // dev it to 2 and add one to it
        }
        else if(guess < random_number){ // if the number is < than the number then
            guess = guess * 2 + 1; // * it with 2 and add one
        }
        tries++; // increase the number of tires
    }
    std::cout << tries;
}

// Game human vs human
void humanVsAI(int range){ // range argument is given to the generate random function
    int random_number = generate_random_number(range); // assigning the random number to variable
    int input = 0; // this var represents the user input
    int tries = 0; // the number of tries user had make to guess the number
    while(input != random_number){
        std::cout << "Enter number: "; // alerting the user to enter a number
        std::cin >> input; // getting the number
        if(input < random_number) // checking if the input > than the random num
            std::cout << "You didn't guess it,you are too low..., try again!\n"; // alerting the user
        else{ // else it will be > than the number
            std::cout << "You didn't guess it,you are too high..., try again!\n"; // alerting the user
        }
        tries++; // increasing tries by one for each try//
    }
    std::cout << "\n\nYou guess it! You need " << tries << " to do this.\n\n";
}

//game Human vs Human
void humanVsHuman(int range){
    int number_to_guess; // the number which must be guessed
    int user_guess; // user input
    int guess;
    std::cout << "Enter number int range 1- "<< range<<": \n"; // alerting the user to enter number
    std::cin >> number_to_guess; // entering number
    for(int i = 0; i < 100;i++){ //Clearing the screen
        std::cout << "\n";
    }
    while(user_guess != number_to_guess){
        guess++;
        std::cout << "Please enter numer:\n"; // alerting the user
        std::cin >> user_guess; // Getting the user input
        if(user_guess < number_to_guess)
            std::cout << "You didn't guess it,you are too low..., try again!\n";
        else if(user_guess > number_to_guess)
            std::cout << "You didn't guess it,you are too high..., try again!\n";
    }
    std::cout << "You guess the number\n";
}
int main(){
    std::string game_type;
    char play_game;
    int range = 0;
    while(1){
        std::cout << "Please enter range(type 100 to leave it as default)\n";
        std::cin >> range;
        std::cout <<"What you want to play AI vs human, human vs human or AI vs AI ?\n";
        std::cin.ignore(); // for get line
        std::getline(std::cin, game_type); // getting the user input
        std::cin.clear(); // clearing
        if(game_type == "AI vs AI" || game_type == "ai vs ai"){ // if the user chose AI vs AI
            std::cout<<"You choosed AI vs AI\n";
            aiVsAI(range); // calling the AI function
        }
        else if(game_type == "human vs ai"
                || game_type  == "ai vs human"
                || game_type == "human vs AI"
                || game_type == "Human vs AI"
                || game_type == "Human vs ai"
                ){ // if the user chossed AI vs human
            std::cout << "You choosed human vs AI\n";
            humanVsAI(range); // calling the human vs human function
        }
        else if(game_type == "human vs human"
                ||game_type == "Human vs Human"
                ||game_type == "Human vs human"
                ||game_type == "human vs Human"){ // if the user choosed human vs human
            std::cout <<"You choose human vs human\n";
            humanVsHuman(range); // calling the human vs human function
        }
        else{ // In case of any error
            std::cerr << "An error occured!";
        }
        std::cout << "Do you want to play another game?\n"; // do you want another game????
        std::cin >> play_game;
        if(play_game == 'y' || play_game == 'Y')
           std::cout <<" starting another game\n";
        else
            break;  // enough playing for now.
    }
    return 0;

}
</code>```


答:
There are many single-threaded reasons to use immutability. For example

Object A contains Object B.

External code queries your Object B and you return it.

Now you have three possible situations:

B is immutable, no problem.

B is mutable, you make a defensive copy and return that. Performance hit but no risk.

B is mutable, you return it.

In the third case the user code may not realize what you have done and may make changes to the object, and by so doing change the internal data of your object with you having no control or visibility of that happening.


问:
Is it allowed to distribute a program which source code is under Ms-PL to paying customers?
What I want to do is bundle XML Notepad (as is, no modifications) with the installation of our commercial product. Instead of telling the customer "go to http://www.microsoft.com/en-us/download/details.aspx?id=7973 and download XML Notepad".

Any one who can offer insight on how to derive the legality of this from the license?

答:
The License

The relevant part:

(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.

I'm no lawyer but I'd say you were ok.


答:
Expanding on what KChaloux summarised very well...

Ideally, you have two types of fields, and hence two types of code using them.  Either fields are immutable, and code doesn't have to take mutability into account; or fields are mutable, and we need to write code that either takes a snapshot (int x = p.x) or gracefully handles such changes.

In my experience, most code falls in between the two, being optimistic code: it freely references mutable data, assuming that the first call to p.x will have the same result as the second call.  And most of the time, this is true, except when it turns out it no longer is.  Oops.

So, really, turn that question around: What are my reasons for making this mutable?

Reducing memory alloc/free?

Mutable by nature? (e.g. counter)

Saves modifiers, horizontal noise? (const/final)

Makes some code shorter/easier? (init default, possibly overwrite after)

Do you write defensive code?  Immutability will save you some copying around.  Do you write optimistic code?  Immutability will spare you the insanity of that weird, impossible bug.


答:
Another benefit of immutability is that it is the first step in rounding up these immutable objects into a pool. Then you can manage them so that you don't create multiple objects that conceptually and semantically represent the same thing. A good example would be Java's String.

It is a well-known phenomenon in linguistic that a few words appear a lot, might appear in other context as well. So instead of creating multiple String object, you can use one immutable. But then you need to keep a pool manager to take care of these immutable objects.

This will save you lot of memory.
This is an interesting article to read as well:
http://en.wikipedia.org/wiki/Zipf%27s_law


问:
Should temporary code be put under version control and how?
Here are some examples of temporary/local code. It is needed in order to work with the codebase, but would be harmful to be part of it:

Project files. Paths may need to be edited in order to reflect the layout on the current PC.

Makefiles. For example optimization may need to be turned off during debugging, but not for the CI server.

Dirty ugly hacks. For example return 7 in the middle of a function, in order to test something, depending on the function, and suspected to break at value of 7. Or 7 is the code of the not yet implemented button, that I am implementing and need to test throughout the life of my branch.

I have tried keeping those in a git commit that I always rebase to the top before pushing to the repo and then push HEAD~. This is quite inconvenient and doesn't work with svn. Stashing scares me even more - "did I remember to pop after pushing??".

Keeping the code out of version control introduces unpleasant noise everytime a commit is being assembled plus it might accidentally get introduced into a commit some friday evening.

What would be a sane solution for such throw-away code?

答:
We use @@ comments in the code to indicate anything not being quite ready, for testing purposes, etc.

That way we can commit, colleagues don't have to wait too long to sync, and can see where there's still work in progress (e.g. understand why a part is not yet fully working).

We do a global search for @@ to prevent any 'leftovers' before entering the final stages of beta testing etc.

Using that discipline, I see no reason to not just commit. This way, we don't have separate branches and only one extra 'protocol' to follow.

As an extra benefit, these todo's (usually small things) are always in the code. The developer working on them can quickly go over them, and there's no need to keep separate lists.

You know how development goes: you are working in one place but you are constantly using your mind as a stack ('I should change that over there when I'm done here'). Just jotting down a quick @@ remark prevents stack overflow.

I even use @@name to indicate issues that I need to discuss with 'name'.


答:
This answer expands on Igby's answer, with an example of the kind of query that can be constructed.

There are definitely trade-offs between the two approaches. However, keeping separate tables for different categories can be queried just as easily in SQL.

```<code>SELECT UNIQUE pid FROM
  (SELECT UNIQUE hobbyref.personid AS pid FROM hobby, hobbyref
    WHERE hobbyref.hobbyid = hobby.id AND hobby.type = 'tv')
  UNION
  (SELECT UNIQUE petref.personid AS pid FROM pet, petref
    WHERE petref.petid = pet.id AND pet.type = 'cat'
  )
</code>```

(Pardon any clumsiness in the SQL. It could probably be expressed more concisely.)

Title: Multiple many to many relations or one option table?

Body:
Let's say I have a database of persons who have some properties. For the sake of this problem let's say all of these properties relate as N-N.

I can either create two tables for each property (one for different values and one for cross-referencing them to the main object).

Or, I can make the following structure:

Basically having just one huge table of values.

Are there any advantages to this approach? Also, does this approach or pattern have a name that I can look up?

UPDATE:
For example, we make classifier pets with properties cat, dog and fish. So one person may have a cat and a dog (or one pet, or none). And we make a classifier hobby with values skiing, skating, football and TV. So Joe has properties cat, dog, and TV. Then cat and dog are pets and TV is hobby.

The question is, is it worthwhile to put this data using this diagram, or is it a better idea to just create pets, pets_xref, hobby, hobby_xref tables?

Body:
This answer expands on Igby's answer, with an example of the kind of query that can be constructed.

There are definitely trade-offs between the two approaches. However, keeping separate tables for different categories can be queried just as easily in SQL.

SELECT UNIQUE pid FROM
  (SELECT UNIQUE hobbyref.personid AS pid FROM hobby, hobbyref
    WHERE hobbyref.hobbyid = hobby.id AND hobby.type = 'tv')
  UNION
  (SELECT UNIQUE petref.personid AS pid FROM pet, petref
    WHERE petref.petid = pet.id AND pet.type = 'cat'
  )

(Pardon any clumsiness in the SQL. It could probably be expressed more concisely.)


答:
Version control should contain code and configuration which is needed to build the application.

This means that:

Temporary stuff which was introduced for a short amount of time (the time required to pinpoint the location of a bug, or to experiment with a feature of a language, for example) shouldn't be in a version control: keep it until you need it, then simply remove it when doing the commit.

Local files which are proper to a particular machine may be kept in a branch.

I would avoid keeping them just locally, since it's too painful to redo all this stuff when your laptop is stolen or a virus forces you to reinstall the OS (and, by the way, you find that your last backup was done two years ago).

On the other hand, be careful with file structure: local config is OK, until it becomes overwhelming, and forces you to make a single change in every file of every of 42 developers participating to the project.

Watch for opportunity to remove the particularities between the machines. It may mean:

Giving an access to a dev SQL server to replace local instances on developers machines,

Using package distribution services like Pypi or npm for public packages and their private counterparts for in-house packages,

Ask members of the team to install the same versions of software,

Make software updates as transparent as possible,

Or make it possible to deploy the OS and the needed software on a machine in one click (plus the time for every developer to install his preferred Vim vs. Emacs, Chrome vs. Firefox, etc.)

So:

Project files. Paths may need to be edited in order to reflect the layout on the current PC.

Why not using the same layout on every PC? Paths within the project should be relative to the project file, which means that it doesn't matter where the project is located. Versions of software and libraries are better to be the same to avoid cryptic bugs which appear on some machines only, and are impossible to reproduce for other members of the team.

Example:

In a project created with Visual Studio, you may find:

The files themselves. Paths being relative, it doesn't matter whether on my machine, the project is located in H:\Development\Hello World Project\ while other members of the team checked out the project into C:\Work\HelloWorld\.

The dependencies, i.e. third party and in-house libraries. Both types should be handled by NuGet which makes all conflicts-related discussions obsolete. If you don't have the same version of the library I have, ask NuGet to update the dependencies. As simple as that (when it works well, which is not always the case).

Note that it is crucial to keep in-house libraries in a private NuGet as well. Having a bunch of libraries stored in a shared folder or sent by e-mail across a team leads to anarchy and depressive CI servers.

The settings. It's crucial that the team shares the same settings. If half of the team decides to treat warnings as errors and half of the team keeps warnings as-is, the members of the first part of the team will spend their time removing warnings generated by the developers from the second part of the team.

The utilities-related settings. Those are tricky, because some members of the team may have installed some utilities, while others haven't.

It is strongly recommended to have the same toolset installed. If some programmers want to use StyleCop, but others don't, the team won't get the job done. If some use Code contracts but others don't, they will have the same issues.

Makefiles. For example optimization may need to be turned off during debugging, but not for the CI server.

Keep several makefiles in version control. It is not unusual to build a debug version on CI server as well and to push it to a client which experiences a tricky bug.

Dirty ugly hacks. For example return 7 in the middle of a function, in order to test something, depending on the function, and suspected to break at value of 7.

I would avoid such code in the first place. In order to test something, use unit tests. If it really takes a few seconds to swap some code for the purpose of debugging, then do it, but you'll remove this code in a few minutes anyway, so there is no need to commit it.

As you describe it, you should write a test. For example, if you want to be sure that:

class TemperatureConverter
{
    public int CelsiusToFahrenheit(int temperature)
    {
        ...
    }
}
```

throws an exception when temperature is inferior to AbsoluteZero constant, you shouldn't play with code itself. Instead, create a unit test which will:

self-document your code,

increase the reliability of your code,

ensure that maintainers can rely on regression testing when modifying the method above,

serve to other developers of your team who may need to do the same test.

Title: Should temporary code be put under version control and how?

Body:
Here are some examples of temporary/local code. It is needed in order to work with the codebase, but would be harmful to be part of it:

Project files. Paths may need to be edited in order to reflect the layout on the current PC.

Makefiles. For example optimization may need to be turned off during debugging, but not for the CI server.

Dirty ugly hacks. For example return 7 in the middle of a function, in order to test something, depending on the function, and suspected to break at value of 7. Or 7 is the code of the not yet implemented button, that I am implementing and need to test throughout the life of my branch.

I have tried keeping those in a git commit that I always rebase to the top before pushing to the repo and then push HEAD~. This is quite inconvenient and doesn't work with svn. Stashing scares me even more - "did I remember to pop after pushing??".

Keeping the code out of version control introduces unpleasant noise everytime a commit is being assembled plus it might accidentally get introduced into a commit some friday evening.

What would be a sane solution for such throw-away code?

Body:
Version control should contain code and configuration which is needed to build the application.

This means that:

Temporary stuff which was introduced for a short amount of time (the time required to pinpoint the location of a bug, or to experiment with a feature of a language, for example) shouldn't be in a version control: keep it until you need it, then simply remove it when doing the commit.

Local files which are proper to a particular machine may be kept in a branch.

I would avoid keeping them just locally, since it's too painful to redo all this stuff when your laptop is stolen or a virus forces you to reinstall the OS (and, by the way, you find that your last backup was done two years ago).

On the other hand, be careful with file structure: local config is OK, until it becomes overwhelming, and forces you to make a single change in every file of every of 42 developers participating to the project.

Watch for opportunity to remove the particularities between the machines. It may mean:

Giving an access to a dev SQL server to replace local instances on developers machines,

Using package distribution services like Pypi or npm for public packages and their private counterparts for in-house packages,

Ask members of the team to install the same versions of software,

Make software updates as transparent as possible,

Or make it possible to deploy the OS and the needed software on a machine in one click (plus the time for every developer to install his preferred Vim vs. Emacs, Chrome vs. Firefox, etc.)

So:

Project files. Paths may need to be edited in order to reflect the layout on the current PC.

Why not using the same layout on every PC? Paths within the project should be relative to the project file, which means that it doesn't matter where the project is located. Versions of software and libraries are better to be the same to avoid cryptic bugs which appear on some machines only, and are impossible to reproduce for other members of the team.

Example:

In a project created with Visual Studio, you may find:

The files themselves. Paths being relative, it doesn't matter whether on my machine, the project is located in H:\Development\Hello World Project\ while other members of the team checked out the project into C:\Work\HelloWorld\.

The dependencies, i.e. third party and in-house libraries. Both types should be handled by NuGet which makes all conflicts-related discussions obsolete. If you don't have the same version of the library I have, ask NuGet to update the dependencies. As simple as that (when it works well, which is not always the case).

Note that it is crucial to keep in-house libraries in a private NuGet as well. Having a bunch of libraries stored in a shared folder or sent by e-mail across a team leads to anarchy and depressive CI servers.

The settings. It's crucial that the team shares the same settings. If half of the team decides to treat warnings as errors and half of the team keeps warnings as-is, the members of the first part of the team will spend their time removing warnings generated by the developers from the second part of the team.

The utilities-related settings. Those are tricky, because some members of the team may have installed some utilities, while others haven't.

It is strongly recommended to have the same toolset installed. If some programmers want to use StyleCop, but others don't, the team won't get the job done. If some use Code contracts but others don't, they will have the same issues.

Makefiles. For example optimization may need to be turned off during debugging, but not for the CI server.

Keep several makefiles in version control. It is not unusual to build a debug version on CI server as well and to push it to a client which experiences a tricky bug.

Dirty ugly hacks. For example return 7 in the middle of a function, in order to test something, depending on the function, and suspected to break at value of 7.

I would avoid such code in the first place. In order to test something, use unit tests. If it really takes a few seconds to swap some code for the purpose of debugging, then do it, but you'll remove this code in a few minutes anyway, so there is no need to commit it.

As you describe it, you should write a test. For example, if you want to be sure that:

class TemperatureConverter
{
    public int CelsiusToFahrenheit(int temperature)
    {
        ...
    }
}

throws an exception when temperature is inferior to AbsoluteZero constant, you shouldn't play with code itself. Instead, create a unit test which will:

self-document your code,

increase the reliability of your code,

ensure that maintainers can rely on regression testing when modifying the method above,

serve to other developers of your team who may need to do the same test.


答:
Project files. Paths may need to be edited in order to reflect the layout on the current PC.

For project files, the best strategy is when you can generate the project file via a script. Add the actual project file to your ignores, and simply re-generate the project file as necessary. For example, in Java projects, I use gradle which can generate an eclipse project.

Makefiles. For example optimization may need to be turned off during
  debugging, but not for the CI server.

You should be able to switch between optimization and debug mode without modifying your Makefile. Instead, use a command line flag, environment variable, or seperate file not in your repository to control that.

Dirty ugly hacks. For example return 7 in the middle of a function, in order to test something, depending on the function, and suspected to break at value of 7. Or 7 is the code of the not yet implemented button, that I am implementing and need to test throughout the life of my branch.

Can't you write a test that induces the suspected failure case?

For most cases, you should be able to adjust your workflow so you don't make these changes to files in your repository. Those files which are changed locally should be added to your project's ignore mechanism and not be in the repository. In some cases, you'll still make temporary changes you don't want put into the repository. For those, add a special sequence like: XXX, and add a pre-commit hook that reject commits that still have it in there.


答:
In Java, C#, and other similar languages, class-type fields may be used either to identify objects, or to encapsulate values or state in those objects, but the languages make no distinction between such usages.  Suppose a class object George has a field of type char[] chars;.  That field may encapsulate a character sequence in either:

An array which will never be modified, nor exposed to any code that might modify it, but to which outside references may exist.

An array to which no outside references exist, but which George may modify freely.

An array which is owned by George, but to which there may exist outside views which would be expect to represent George's current state.

Additionally, the variable may, instead of encapsulating a character sequence, encapsulate a live view to a character sequence owned by some other object

If chars presently encapsulates the character sequence [w i n d], and George wants chars to encapsulate the character sequence [w a n d], there are a number of things George could do:

A. Construct a new array containing the characters [w a n d] and change chars to identify that array rather than the old one.

B. Identify somehow a pre-existing character array which will always hold the characters [w a n d] and change chars to identify that array rather than the old one.

C. Change the second character of the array identified by chars to an a.

In case 1, (A) and (B) are safe ways to achieve the desired result.  In case (2), (A) and (C) are safe, but (B) would not be [it wouldn't cause immediate problems, but since George would assume that it has ownership of the array, it would assume that it could change the array at will].  In case (3), choices (A) and (B) would break any outside views, and thus only choice (C) is correct.  Thus, knowing how to modify the character sequence encapsulated by the field requires knowing which semantic type of field it is.

If instead of using a field of type char[], which encapsulates a potentially-mutable character sequence, code has used type String, which encapsulates an immutable character sequence, all of the above issues go away.  All fields of type String encapsulate a sequence of characters using a sharable object that will never change.  Consequently, if a field of type String encapsulates "wind", the only way to make it encapsulate "wand" is to make it identify different object--one which holds "wand".  In cases where code holds the only reference to the object, mutating the object may be more efficient than creating a new one, but any time a class is mutable it is necessary to distinguish among the different ways by which it can encapsulate value.  Personally I think Apps Hungarian should have been used for this (I would consider the four uses of char[] to be semantically-distinct types, even though the type system considers them identical--exactly the sort of situation where Apps Hungarian shines), but since it wasn't the easiest way to avoid such ambiguities is to design immutable types that only encapsulate values one way.


答:
All code is temporary. When I'm making changes I will introduce placeholders occasionally - that icon that I drew waiting for the real one from the designer, the function I know will call the library that my colleague is writing and hasn't yet finished (or started), the extra logging that will be removed or otherwise made conditional, the bugs that I will get around to fixing once they've been noticed by the test team, etc

So check everything in. Use a feature branch for all your development, then you can merge the final version into trunk and no-one will need to know what hacks and bodges and fixes you made during your development cycle, they'll only need to see the final version. But if you've committed to your branch regularly, you'll be able to see the things that were worth keeping if a day went spectacularly wrong, or you continued coding after a lunchtime down the pub.

Version control is not a artifact repository or document storage system. Its about holding the history of changes. Stick everything you like in there becuase one day you might want to see what it was, and those are the days you realise what your SCM is truly about.

PS. Truly temporary files (eg .obj or build artifacts) have no place in your SCM. These are things that have no value to anyone. You can tell what they are - if you delete them you don't mind, or even notice they're gone.


问:
`trigger_error` vs `throw Exception` in the context of PHP's magic methods
I'm having a debate with a colleague over the correct usage (if any) of trigger_error in the context of magic methods. Firstly, I think that trigger_error should be avoided except for this one case.

Say we have a class with one method foo()

```<code>class A {
    public function foo() {
        echo 'bar';
    }
}
</code>```

Now say we want to provide the exact same interface but use a magic method to catch all method calls

```<code>class B {
    public function __call($method, $args) {
        switch (strtolower($method)) {
        case 'foo':
            echo 'bar';
            break;
        }
    }
}

$a = new A;
$b = new B;

$a->foo(); //bar
$b->foo(); //bar
</code>```

Both classes are the same in the way they respond to foo() but differ when calling an invalid method.

```<code>$a->doesntexist(); //Error
$b->doesntexist(); //Does nothing
</code>```

My argument is that magic methods should call trigger_error when a unknown method is caught

```<code>class B {
    public function __call($method, $args) {
        switch (strtolower($method)) {
        case 'foo':
            echo 'bar';
            break;
        default:
            $class = get_class($this);
            $trace = debug_backtrace();
            $file = $trace[0]['file'];
            $line = $trace[0]['line'];
            trigger_error("Call to undefined method $class::$method() in $file on line $line", E_USER_ERROR);
            break;
        }
    }
}
</code>```

So that both classes behave (almost) identically

```<code>$a->badMethod(); //Call to undefined method A::badMethod() in [..] on line 28
$b->badMethod(); //Call to undefined method B::badMethod() in [..] on line 32
</code>```

My use-case is an ActiveRecord implementation. I use __call to catch and handle methods that essentially do the same thing but have modifiers such as Distinct or Ignore, e.g.

```<code>selectDistinct()
selectDistinctColumn($column, ..)
selectAll()
selectOne()
select()
</code>```

or

```<code>insert()
replace()
insertIgnore()
replaceIgnore()
</code>```

Methods like where(), from(), groupBy(), etc. are hard-coded.

My argument is highlighted when you accidentally call insret(). If my active record implementation hardcoded all of the methods then it would be an error.

As with any good abstraction, the user should be unaware of the implementation details and rely solely on the interface. Why should the implementation that uses magic methods behave any differently? Both should be an error.

答:
IMO, this is a perfectly valid use case for trigger_error :

```<code>function handleError($errno, $errstring, $errfile, $errline, $errcontext) {
    if (error_reporting() & $errno) {
        // only process when included in error_reporting
        return handleException(new \Exception($errstring, $errno));
    }
    return true;
}

function handleException($exception){
    // Here, you do whatever you want with the generated
    // exceptions. You can store them in a file or database,
    // output them in a debug section of your page or do
    // pretty much anything else with it, as if it's a
    // normal variable

    switch ($code) {
        case E_ERROR:
        case E_CORE_ERROR:
        case E_USER_ERROR:
            // Make sure script exits here
            exit(1);
        default:
            // Let script continue
            return true;
    }
}

// Set error handler to your custom handler
set_error_handler('handleError');
// Set exception handler to your custom handler
set_exception_handler('handleException');

// ---------------------------------- //

// Generate warning
trigger_error('This went wrong, but we can continue', E_USER_WARNING);

// Generate fatal error :
trigger_error('This went horrible wrong', E_USER_ERROR);
</code>```

Using this strategy, you get the $errcontext parameter if you do $exception->getTrace() within the function handleException. This is very useful for certain debugging purposes.

Unfortunately, this works only if you use trigger_error directly from your context, which means you can't use a wrapper function/method to alias the trigger_error function (so you can't do something like function debug($code, $message) { return trigger_error($message, $code); } if you want the context data in your trace).

I have been looking for a better alternative, but so far I haven't found any.

Body:
IMO, this is a perfectly valid use case for trigger_error :

function handleError($errno, $errstring, $errfile, $errline, $errcontext) {
    if (error_reporting() & $errno) {
        // only process when included in error_reporting
        return handleException(new \Exception($errstring, $errno));
    }
    return true;
}

function handleException($exception){
    // Here, you do whatever you want with the generated
    // exceptions. You can store them in a file or database,
    // output them in a debug section of your page or do
    // pretty much anything else with it, as if it's a
    // normal variable

    switch ($code) {
        case E_ERROR:
        case E_CORE_ERROR:
        case E_USER_ERROR:
            // Make sure script exits here
            exit(1);
        default:
            // Let script continue
            return true;
    }
}

// Set error handler to your custom handler
set_error_handler('handleError');
// Set exception handler to your custom handler
set_exception_handler('handleException');

// ---------------------------------- //

// Generate warning
trigger_error('This went wrong, but we can continue', E_USER_WARNING);

// Generate fatal error :
trigger_error('This went horrible wrong', E_USER_ERROR);

Using this strategy, you get the $errcontext parameter if you do $exception->getTrace() within the function handleException. This is very useful for certain debugging purposes.

Unfortunately, this works only if you use trigger_error directly from your context, which means you can't use a wrapper function/method to alias the trigger_error function (so you can't do something like function debug($code, $message) { return trigger_error($message, $code); } if you want the context data in your trace).

I have been looking for a better alternative, but so far I haven't found any.


问:
How do you handle specific networking exceptions in Haskell?
I have the following to try and connect to a server:

```<code>testAddress :: HostName -> Int -> IO (Maybe Handle)
testAddress host iPort = do
    let port = PortNumber $ fromIntegral iPort
    putStrLn $ "Testing - Host: " ++ host ++ ", Port: " ++ show iPort
    result <- try $ connectTo host port
    case result of
        Left (SomeException e) -> return Nothing
        Right h -> do
            putStrLn $ "Connected to " ++ host
            return $ Just h
</code>```

I made the exception to catch "SomeException", but I know that's not the proper way to do it; as it will catch everything, and you can't handle individual cases. I can't find the names of specific network exceptions though. There doesn't appear to be any documentation for the Network package, and a every example I can find on google just uses "SomeException". If I try and connect to a random host and port, and I don't attempt to catch anything, I get the error:
"* Exception: connect: failed (Connection timed out (WSAETIMEDOUT))"
But it doesn't seem to give me the exact name of the exception to try and catch. I thought it might be "WSAETIMEOUT", but when I tried catching that, I got a compilation error saying that it couldn't find the constructor for "WSAETIMEOUT".
What should I do. I don't want to just catch everything and treat it the same, because then I don't know whats going on.

Thank you

答:
You can pattern-match on a specific exception type like this:

```<code>testAddress :: HostName -> Int -> IO (Maybe Handle)
testAddress host iPort = do
    let port = PortNumber $ fromIntegral iPort
    putStrLn $ "Testing - Host: " ++ host ++ ", Port: " ++ show iPort
    result <- try $ connectTo host port
    case result of
        Left (e :: MyExceptionType) -> return Nothing
        Right h -> do
            putStrLn $ "Connected to " ++ host
            return $ Just h
</code>```

This will actually cause Haskell to infer that the type of result is Either MyExceptionType Handle, and try will therefore only catch exceptions of MyExceptionType, propagating all others unchanged.

As for the particular exception types used by the network package, I couldn't find any documentation on them either, but since Typeable is a superclass of Exception, you should be able to print out the type of any exception you catch, which should be useful.

Body:
You can pattern-match on a specific exception type like this:

testAddress :: HostName -> Int -> IO (Maybe Handle)
testAddress host iPort = do
    let port = PortNumber $ fromIntegral iPort
    putStrLn $ "Testing - Host: " ++ host ++ ", Port: " ++ show iPort
    result <- try $ connectTo host port
    case result of
        Left (e :: MyExceptionType) -> return Nothing
        Right h -> do
            putStrLn $ "Connected to " ++ host
            return $ Just h

This will actually cause Haskell to infer that the type of result is Either MyExceptionType Handle, and try will therefore only catch exceptions of MyExceptionType, propagating all others unchanged.

As for the particular exception types used by the network package, I couldn't find any documentation on them either, but since Typeable is a superclass of Exception, you should be able to print out the type of any exception you catch, which should be useful.


问:
Is there a way to use RAII techniques in COM?
I am caught between two conceptual models of how to construct objects, and am having trouble working out what standard I want to adopt.

I prefer to program in .NET and often try to use RAII and read-only properties to make immutable objects with their data passed in through constructor parameters.  This has been a major advance compared to the VB6 days when we had to simulate constructors and by convention call "Init" or "Factory.Create" to get objects into a good state.

However, I am often making COM-callable wrappers to let me call functions via Automation from other applications.  As you probably know, COM wants objects to have a constructor without any parameters.  This is a dissonance with the RAII/immutable scheme that I have been using with such success in the .NET world.

I remember older object models like ADO where you would usually instantiate an object, set properties like ConnectionString, then call Open.  The object could be immutable not via a ReadOnly declaration, but via throwing an "Can't change while open" exception on the property setter.

Is this the best pattern to use for COM?  Am I missing a better way to skin this cat?  Since RAII came out of the C++ community, how do they handle COM being based on a different initialization scheme?

答:
RAII doesn't necessarily mean you have a fully working object. It means you have a fully constructed object that is ready to work. So if your object needs an initialisation call to set its state, that's fine - its nothing to do with RAII that ensures you have an object that is possible to fill with state (ie its not half-built in some uncertain state).

I think its best to think of this as the difference between application and system state. ie the object is fully ready to go as far as the system is concerned, its correctly laid out in memory etc. Then your application can work with it.

Read this Martin Fowler article that discusses the difference between creating an object and initialising it via its constructor or subsequent property setting (eg Initialisation).

So. given you cannot create a COM object with constructor-style property setting, you have to either wrap its construction in an object you do have control over (so the constructor of your object only returns a valid object if the COM dependent is created and initialised)

C++ would do the same kind of thing, only C++ tends to be more concerned about lifetime using RAII (where the object is properly destroyed when it goes out of scope) than about initialisation. Many people wrap a COM object in a smart pointer (eg CComPtr to name one) but this still doesn't set its properties like you want. There's still nothing stopping you wrapping the smart pointer further with a constructor that does it all.