问:
Better way of handling pre conditions and logging
1. Imagine you have the following:

void Foo::doFoo()
{
    if (!isConditionValid())
    {
        log("doFoo not possible because condition is not valid");
        return;
    }

    if (!isTheOtherConditionValid())
    {
        log("doFoo not possible because the other condition is not valid");
        return;
    }

    // do Foo actions
}
```

<p>Is there a better way to format the code?
Really often, I have 1,2 or 3 conditions, and I find it really repetitive to have this structure.</p>

<p><strong>2.</strong> What if I have the doBar method, that has the exact same conditions, so we would have:</p>

<pre class="lang-cpp prettyprint-override"><code>void Foo::doBar()
{
    if (!isConditionValid())
    {
        log("doBar not possible because condition is not valid");
        return;
    }

    if (!isTheOtherConditionValid())
    {
        log("doBar not possible because the other condition is not valid");
        return;
    }

    // do Bar actions
}
</code>```

I feel like I should refactor those conditions, but I find it difficult to find the name of the method. If call the method "areConditionsValid", I don't expect it to log anything, just to return a boolean. So the following doesn't seem right to me:

bool Foo::areConditionsValid(String action)
{
    if (!isConditionValid())
    {
        log(action + " not possible because condition is not valid");
        return false;
    }

    if (!isTheOtherConditionValid())
    {
        log(action + " not possible because the other condition is not valid");
        return false;
    }

    return true;
}
```

Because it does more than what it says it does.

I can't call it checkConditionsAndLog() because it is not good practice to have a "And" in the method's name, it is a good way to see that it's doing more than it should do...

What's the best way to refactor this?

The same applies if there is only one condition to check.

PS: It's in C++

答:
There is some ambiguity with the term "preconditions":

it could mean "do not call the function if these are not valid" (that is, something that client code should handle)

it could mean "if these are not valid in the function, (log message and) compute nothing"

it could mean "if these are not valid exit the application"

When implementing this, you should rarely decide on how to handle the error, at the place where it occurs; instead, you should throw an exception and let client code decide.

With this, your code could become:

```<code>void Foo::AssertPrecondition(bool condition, std::string msg)
{
    if(!condition)
        throw std::runtime_error{ std::move(msg) };
}

void Foo::doFoo()
{
    AssertPrecondition(isConditionValid(),
        "doFoo not possible because condition is not valid");
    AssertPrecondition(isTheOtherConditionValid(),
        "doFoo not possible because the other condition is not valid");

    // TODO: implement valid execution branch
}
</code>```

From this point onwards, client code can decide what happens when an error occurs.

Also, as a rule, if you have more than one repeating line in code, you should refactor those to a separate function.

Body:
There is some ambiguity with the term "preconditions":

it could mean "do not call the function if these are not valid" (that is, something that client code should handle)

it could mean "if these are not valid in the function, (log message and) compute nothing"

it could mean "if these are not valid exit the application"

When implementing this, you should rarely decide on how to handle the error, at the place where it occurs; instead, you should throw an exception and let client code decide.

With this, your code could become:

void Foo::AssertPrecondition(bool condition, std::string msg)
{
    if(!condition)
        throw std::runtime_error{ std::move(msg) };
}

void Foo::doFoo()
{
    AssertPrecondition(isConditionValid(),
        "doFoo not possible because condition is not valid");
    AssertPrecondition(isTheOtherConditionValid(),
        "doFoo not possible because the other condition is not valid");

    // TODO: implement valid execution branch
}

From this point onwards, client code can decide what happens when an error occurs.

Also, as a rule, if you have more than one repeating line in code, you should refactor those to a separate function.


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答: The C++ I use is called C with classes!</p>

ContentLicense: CC BY-SA 3.0

Body: The C++ I use is called C with classes!

OwnerDisplayName: willspeak

ContentLicense: CC BY-SA 2.5


问:
Determine frequency-range that matches closest to input list of frequencies

    Since this question is not about "code not working", I'm asking my first question here instead of StackOverflow. Inform me if any required information is missing from the question.

Setup:

I have two dictionaries of type Dictionary<int, int> where the keys are a range from 1 to n and the values are the frequencies of those numbers. For example:

```<code>var frequenciesA = new Dictionary<int, int>
{
    { 1, 3 },
    { 2, 5 },
    { 3, 4 }
};

var frequenciesB = new Dictionary<int, int>
{
    { 1, 1 },
    { 2, 3 },
    { 3, 4 }
};
</code>```

Input:

Now I will get a list of integers as an input, in the range of 1 to n, like this:

```<code>var numbers = new List<int> { 1, 2, 3, 3, 2, 1, 1, 2, 3, 1, 2, 2 };
</code>```

I also create a frequency-dictionary from this list with following code:

```<code>var frequenciesFromInput = Enumerable.Range(1, 3)
                                     .ToDictionary(x => x,
                                                   x => numbers.Count(y => y == x));
</code>```

This would result in following key-value pairs:

```<code>K  V
----
1  4
2  5
3  3
</code>```

Problem:

Suppose I needed to determine to which from the other dictionaries (A or B) the frequencies equals, that'd be easy: take the values of the dictionaries as a list and use the Enumerable.SequenceEqual<T> method.

But in my case I need to determine which dictionary (A or B) matches closest to the frequencies of the input dictionary. Visualizing this makes it easier to understand. Here are the charts for the constant frequencies of dictionary A and B:

And here's the chart of the input dictionary:

As you can see the frequencies of A match closer than to those of B.

Question:

How would I start creating a method/algorithm to determine which dictionary (A or B) is closer to that of the input dictionary. I'm not asking for a full implementation, just a little push as for now I have no idea where and how to start on this.

Only thing I could think of was some variation on the Knapsack problem, but I'm not sure I'm on the right path there.

答:
Vector subtraction should be enough. And find the mean (or root mean square) of the absolute differences-- the smaller, the closer match.

EDIT:

Example:

** Root mean squared = Sqr(Sum(xi²)/n) where xi are Differences


问:
How can I manage trash users?
I created a system which hopefully will have many users. We are afraid our user database will be filled by "trash users" which take high-demand usernames, or maybe they just register and never come back.

I know this is common, I do this myself, as I have 3 google accounts, but I only use 1. How can a large website manage trash users or never coming back users like this?

答:
Separate login credentials from display names

Allow users to log in with their email address or existing account from a site which provides such a service (e.g. Google or Facebook). If you really want to have users come up with a new username, that works, too.

Then, before interacting with the system further (or as part of registration), ask users to pick a display name. Since this name is separate from login credentials, you are free to reclaim it if the user becomes inactive and can, upon their return, make them select a new name. As a bonus, you can let users change their display name at will.

This does not work as well (but isn't really all that bad) for systems where you are saving long-term discussions between many users - it can be difficult to parse a conversation between a handful of users a few months or years later when two of them have gone inactive and lost their display names (replaced with inactive user #123 and #186 respectively) but have still referred to their old names in text. It can also lead to users impersonating each other, though there are many strategies to combat this.

This is not a very novel idea. Stack Overflow does the separation (though I don't think names are ever reclaimed or even unique), several online games also implement the reclamation aspect.

ContentLicense: CC BY-SA 4.0

Title: How can I manage trash users?


问:
Designing CRUD part of an HTTP API
This question is in the context of web based applications. A web server
exposing an HTTP api for clients (e.g. running in a browser but not
necessarily). Usually the web server would be connected to somekind of
datastorage.

My concern is the API exposed by the HTTP server, and how to design it.

I find that, often, a big part of api exposed to the client is just a
CRUD interface to the datastorage. For example, the api almost always
contains things like:

```<code>- get_all_users()
- get_this_user(id)
- create_new_user(name, email, phone, password)
- update_user(id, name?, email?, phone?, password?)
- delete_user(id)
</code>```

This is not all the API does, but it something that is common to a lot
of APIs I've worked with.

Depending on what the client needs, I often end up with more and more
things in the API such as these:

```<code>- get_user_by_email(email)
- get_all_users_along_with_number_of_lincenses_for_each()
- delete_all_these_users_at_once(array [])
- get_users_whose_profile_is(profile_name)
- get_names_of_users_who_are_admin_profiles()
- .... etc
</code>```

In other words, the client often needs to do joins, filter, and sort the
data in all kinds of ways.

Which has led me to overly bloated APIs (just like the one above)
supporting all kinds of options for filtering, sorting, and joining with
data from other tables.

The resulting API is too complex for both the client to use and learn
and for the server to maintain and test.

(IMO the Zabbix HTTP api suffers from this syndrom).

Questions:

Do you have similar experience?

Do you have some pointers as to how to strike a good balance between
API completeness and complexity.

PS. I'm aware of REST, but I don't find it resolves the problem, the api
provided is still very basic, and doesn't solve the
get_users_along_with_number_of_licenses() or the
get_names_of_users_which_are_admin() api calls.;

答:
I suggest that you 1) learn what other REST APIs do, and 2) consider OData

I love Odata because it supports every scenario you listed in one single API call.  I'm biased though, because in C# you can implement an Odata server in just a few lines of code if you use the Entity Framework.  There's also client side libraries that can format OData URLs.

Let me apply some of your query examples to OData:

get_user_by_email(email)

http://server/Users$filter=email eq 'joe@company.com'

get_all_users_along_with_number_of_lincenses_for_each()

http://server/Users$filter=email eq 'joe@company.com'/Licenses

get_names_of_users_who_are_admin_profiles()

http://server/Users$filter=admin eq true$select=Name

Overall, OData basically maps everything you would find in a SQL select clause into the Query string.  The only complaint I have about it is that it is a bit too powerful so you need to do some work on the server side to make sure someone doesn't do a complicated query for a million records.  Limit the number of results, limit the time the query can run, etc.

With your delete example, there are a some common ways to pass arrays.  If you read the documentation on Swagger you can get an idea of the different ways that people tend to pass arrays as arguments.  Swagger lists comma separated values, space separated, tab separated, pipe separated, and repeating the parameter multiple times. CSV is the default, so that tells me that people tend to use it a lot.  ASP.NET MVC natively maps the last example to an array.  So consider:

delete_all_these_users_at_once(array [])

HTTP DELETE http://server/Users?id=7&id=14&id=8375
or
HTTP DELETE http://server/Users?id=7,14,8375

Title: Designing CRUD part of an HTTP API


问:
How do I bundle library files for use in branches?
I work at a company which has it's source code managed using subversion. Our code base is huge (800MB) but we want to work with branching. For what I noticed is that when branching, SVN just duplicates every file which makes it almost impossible to branch because of the space.

I would like to separate our library and other not often changed files, so it can be loaded in each branch and stored only once. How can I structure our repository so that branching doesn't copy every single file in the repository?

I was looking at svn:externals, but I don't know if that's the way to go.

答:
Some caveats:

You really shouldn't be storing libraries in your source-control system. Especially third-party libraries. Depending on the language and tools that you're using, there are a lot of ways to avoid doing so, but that's another question.

Recognize that the Subversion repository uses the equivalent of links internally, so the only time a file is actually duplicated is when it's changed. If you commit a file in version 100 of the repository, every branch based on that version will reference the same file (unless and until you commit a new version).

You don't want Subversion to create symlinks on the client. You want each branch to be self-contained, so that you don't accidentally change a shared file. However, be aware that Subversion will manage symlinks that you create.

With those in mind, and with the goal of moving toward a world where you don;t keep your libraries in the source repository, I recommend creating separate directories at the top of your repository:

```<code>/libraries
/project-1
    /trunk
    /tags
    /branches
</code>```

This is one of the under-appreciated features of Subversion: you can check out any arbitrary subtree of the repository into any arbitrary directory on your local filesystem.

So, how do you deal with separation of libraries and source? That again depends on your language and tools. It can be as simple (and ugly, and barely maintainable) as a lib directory in your project that contains symlinks back to the libraries directory.

Better is to use a build tool that gets its library references from a configuration file. This will let you easily add libraries into the repository, and lets different project versions use different sets of libraries.

Body:
Some caveats:

You really shouldn't be storing libraries in your source-control system. Especially third-party libraries. Depending on the language and tools that you're using, there are a lot of ways to avoid doing so, but that's another question.

Recognize that the Subversion repository uses the equivalent of links internally, so the only time a file is actually duplicated is when it's changed. If you commit a file in version 100 of the repository, every branch based on that version will reference the same file (unless and until you commit a new version).

You don't want Subversion to create symlinks on the client. You want each branch to be self-contained, so that you don't accidentally change a shared file. However, be aware that Subversion will manage symlinks that you create.

With those in mind, and with the goal of moving toward a world where you don;t keep your libraries in the source repository, I recommend creating separate directories at the top of your repository:

/libraries
/project-1
    /trunk
    /tags
    /branches

This is one of the under-appreciated features of Subversion: you can check out any arbitrary subtree of the repository into any arbitrary directory on your local filesystem.

So, how do you deal with separation of libraries and source? That again depends on your language and tools. It can be as simple (and ugly, and barely maintainable) as a lib directory in your project that contains symlinks back to the libraries directory.

Better is to use a build tool that gets its library references from a configuration file. This will let you easily add libraries into the repository, and lets different project versions use different sets of libraries.


答:
This is more of a UX problem, rather than a programming problem.

But the solution is simple: don't use the user's username as their display name. Basically every major service uses this method: Stack Exchange, Google, Youtube, Steam, everything.

This comes with two major advantages:

1) Users can choose whatever name they want, even if it's already taken. Duplicate users don't usually cause any confusion since users typically have avatars or IDs.

2) Security. You're not telling your username to the world, begging people to bruteforce your account.

Title: How can I manage trash users?

Body:
I created a system which hopefully will have many users. We are afraid our user database will be filled by "trash users" which take high-demand usernames, or maybe they just register and never come back.

I know this is common, I do this myself, as I have 3 google accounts, but I only use 1. How can a large website manage trash users or never coming back users like this?


答:
The googleable name for your problem is creating a statistical classifier.  It's quite a large topic.  You can try a basic vector subtraction like kunthet's answer and see if it works for your application.  However, if you end up with a lot of incorrect classifications, there are many considerations that can drastically improve the accuracy of your classifier.

For example, perhaps you have a bunch of documents, and you want to know if they were written by Pharrell or Shakespeare.  Straight vector subtraction will disproportionately weight words with large coincidental frequency differences like the word the, compared to less frequent words that are much more useful in classification, like forsooth or happy.  There are feature extraction algorithms that can determine those more useful words automatically, and classification algorithms that can weight them appropriately.

By all means, try the simple algorithm first.  Just be aware there are a lot of subtle pitfalls in this sort of problem, that you might have to delve deeper to solve.

Title: Determine frequency-range that matches closest to input list of frequencies

Body:
    Since this question is not about "code not working", I'm asking my first question here instead of StackOverflow. Inform me if any required information is missing from the question.

Setup:

I have two dictionaries of type Dictionary<int, int> where the keys are a range from 1 to n and the values are the frequencies of those numbers. For example:

```<code>var frequenciesA = new Dictionary<int, int>
{
    { 1, 3 },
    { 2, 5 },
    { 3, 4 }
};

var frequenciesB = new Dictionary<int, int>
{
    { 1, 1 },
    { 2, 3 },
    { 3, 4 }
};
</code>```

Input:

Now I will get a list of integers as an input, in the range of 1 to n, like this:

```<code>var numbers = new List<int> { 1, 2, 3, 3, 2, 1, 1, 2, 3, 1, 2, 2 };
</code>```

I also create a frequency-dictionary from this list with following code:

```<code>var frequenciesFromInput = Enumerable.Range(1, 3)
                                     .ToDictionary(x => x,
                                                   x => numbers.Count(y => y == x));
</code>```

This would result in following key-value pairs:

```<code>K  V
----
1  4
2  5
3  3
</code>```

Problem:

Suppose I needed to determine to which from the other dictionaries (A or B) the frequencies equals, that'd be easy: take the values of the dictionaries as a list and use the Enumerable.SequenceEqual<T> method.

But in my case I need to determine which dictionary (A or B) matches closest to the frequencies of the input dictionary. Visualizing this makes it easier to understand. Here are the charts for the constant frequencies of dictionary A and B:

And here's the chart of the input dictionary:

As you can see the frequencies of A match closer than to those of B.

Question:

How would I start creating a method/algorithm to determine which dictionary (A or B) is closer to that of the input dictionary. I'm not asking for a full implementation, just a little push as for now I have no idea where and how to start on this.

Only thing I could think of was some variation on the Knapsack problem, but I'm not sure I'm on the right path there.


问:
Can a pimpl variation be implemented without any performance penalty?
One of the issues of pimpl is the performance penalty of using it (additional memory allocation, non-contiguous data members, additional indirections, etc..). I would like to propose a variation on the pimpl idiom that will avoid these performance penalties at the expense of not getting all the benefits of pimpl. The idea is to leave all private data members in the class itself and move only the private methods to the pimpl class.
The benefit compared to basic pimpl is that the memory remains contiguous (no additional indirection). The benefits compared to not using pimpl at all are:

It hides the private functions.

You can structure it so that all these functions will have internal linkage and allow the compiler to more aggressively optimize it.

So my idea is to make the pimpl inherit from the class itself (sounds a bit crazy I know, but bear with me).
It would look something like this:

In A.h file:

```<code>class A
{
    A();
    void DoSomething();
protected:  //All private stuff have to be protected now
    int mData1;
    int mData2;
//Not even a mention of a PImpl in the header file :)
};
</code>```

In A.cpp file:

```<code>#define PCALL (static_cast<PImpl*>(this))

namespace //anonymous - guarantees internal linkage
{
struct PImpl : public A
{
    static_assert(sizeof(PImpl) == sizeof(A),
                  "Adding data members to PImpl - not allowed!");
    void DoSomething1();
    void DoSomething2();
    //No data members, just functions!
};

void PImpl::DoSomething1()
{
    mData1 = bar(mData2); //No Problem: PImpl sees A's members as it's own
    DoSomething2();
}

void PImpl::DoSomething2()
{
    mData2 = baz();
}

}
A::A(){}

void A::DoSomething()
{
    mData2 = foo();
    PCALL->DoSomething1(); //No additional indirection, everything can be completely inlined
}
</code>```

As far as I see there are absolutely no performance penalties in using this vs no pimpl and some possible performance gains and cleaner header file interface. One disadvantage this has vs standard pimpl is that you can't hide the data members so changes to those data members will still trigger a recompilation of everything that depends on the header file. But the way I see it, it's either get that benefit or the performance benefit of having the members contiguous in memory (or do this hack - "Why Attempt #3 is Deplorable"). Another caveat is that if A is a templated class the syntax gets annoying (you know, you can't use mData1 directly, you need to do this->mData1, and you need to start using the typename and maybe template keywords for dependent types and templated types, etc.). Yet another caveat is that you can no longer use private in the original class, only protected members, so you can't restrict access from any inheriting class, no just the pimpl. I tried but couldn't get around this issue. For example, I tried making the pimpl a friend template class in the hopes of making the friend declaration broad enough to allow me to define the actual pimpl class in an anonymous namespace, but that just doesn't work. If anyone has any idea of how to keep the data members private and still allow an inheriting pimpl class defined in an anonymous namepsace to access those, I'd really like to see it! That would eliminate my main reservation from using this.

I feel though, that these caveats are acceptable for the benefits of what I propose.

I tried looking online for some reference to this "function-only pimpl" idiom but couldn't find anything. I'm really interested in what people think about this. Are there other issues with this or reasons I shouldn't use this?

UPDATE:

I've found this proposal that more or less tries to accomplish exactly what I am, but doing so by changing the standard. I completely agree with that proposal and hope it will make it into the standard (I know nothing of that process so I have no idea of how likely that's to happen). I'd much rather have it possible to do this through a built in language mechanism. The proposal also explains the benefits of what I'm trying to achieve much better than me. It also doesn't have the issue of breaking encapsulation like my suggestion has (private -> protected). Still, until that proposal makes it into the standard (if that ever happens), I think my suggestion makes it possible to get those benefits, with the caveats I listed.

UPDATE2:

One of the answers mentions LTO as a possible alternative to getting some of the benefits (more aggressive optimizations I'm guessing). I'm not really sure exactly what goes on in various compiler optimization passes but I do have a bit of experience with the resulting code (I use gcc). Simply putting the private methods in the original class will force those to have external linkage.

I might be wrong here, but the way I interpret that is that the compile-time optimizer cannot eliminate the function even if all its call instances are completely inlined inside that TU. For some reason even LTO refuses to get rid of the function definition even if it seems that all the call instances in the entire linked binary are all inlined. I found some references stating that it's because the linker doesn't know if you'll somehow still call the function using function pointers (though I don't understand why the linker can't figure out that the address of that method is never taken).

This is not the case if you use my suggestion and put those private methods in a pimpl inside an anonymous namespace. If those get inlined, the functions will NOT appear in (with -O3, that includes -finline-functions) the object file.

The way I understand it, the optimizer, when deciding whether or not to inline a function, takes into account its impact on code size. So, using my suggestion I'm making it slightly "cheaper" for the optimizer to inline those private methods.

答:
The selling points of the Pimpl pattern are:

total encapsulation: there are no (private) data members mentioned in the header file of the interface object.

stability: until you break the public interface (which in C++ includes private members), you'll never have to recompile code that depends on the interface object. This makes the Pimpl a great pattern for libraries that don't want their users to recompile all code on every internal change.

polymorphism and dependency injection: the implementation or behaviour of the interface object can be easily swapped out at runtime, without requiring dependent code to be recompiled. Great if you need to mock something for an unit test.

To this effect, the classic Pimpl consists of three parts:

An interface for the implementation object, which must be public, and use virtual methods for the interface:

class IFrobnicateImpl
{
public:
    virtual int frobnicate(int) const = 0;
};
```

<p>This interface is required to be stable.</p></li>
<li><p>An interface object that proxies to the private implementation. It does not have to use virtual methods. The only allowed member is a pointer to the implementation:</p>

<pre class="lang-cpp prettyprint-override"><code>class Frobnicate
{
    std::unique_ptr<IFrobnicateImpl> _impl;
public:
    explicit Frobnicate(std::unique_ptr<IFrobnicateImpl>&& impl = nullptr);
    int frobnicate(int x) const { return _impl->frobnicate(x); }
};

...

Frobnicate::Frobnicate(std::unique_ptr<IFrobnicateImpl>&& impl /* = nullptr */)
: _impl(std::move(impl))
{
    if (!_impl)
        _impl = std::make_unique<DefaultImplementation>();
}
</code>```

The header file of this class must be stable.

At least one implementation

The Pimpl then buys us a great deal of stability for a library class, at the cost of one heap allocation and additional virtual dispatch.

How does your solution measure up?

It does away with encapsulation. Since your members are protected, any subclass can mess with them.

It does away with interface stability. Whenever you change your data members – and that change is just one refactoring away – you'll have to recompile all dependent code.

It does away with the virtual dispatch layer, preventing easy swapping of the implementation.

So for every objective of the Pimpl pattern, you fail to fulfil this objective. It is therefore not reasonable to call your pattern a variation of the Pimpl, it is much more an ordinary class. Actually, it's worse than an ordinary class because your member variables are private. And because of that cast which is a glaring point of fragility.

Note that the Pimpl pattern is not always optimal – there's a tradeoff between stability and polymorphism on the one hand, and memory compactness on the other. It is semantically impossible for a language to have both (without JIT compilation). So if you're micro-optimizing for memory compactness, clearly the Pimpl is not a suitable solution for your use case. You'll also probably stop using half the standard library, since these awful string and vector classes involve dynamic memory allocations ;-)

Body:
The selling points of the Pimpl pattern are:

total encapsulation: there are no (private) data members mentioned in the header file of the interface object.

stability: until you break the public interface (which in C++ includes private members), you'll never have to recompile code that depends on the interface object. This makes the Pimpl a great pattern for libraries that don't want their users to recompile all code on every internal change.

polymorphism and dependency injection: the implementation or behaviour of the interface object can be easily swapped out at runtime, without requiring dependent code to be recompiled. Great if you need to mock something for an unit test.

To this effect, the classic Pimpl consists of three parts:

An interface for the implementation object, which must be public, and use virtual methods for the interface:

class IFrobnicateImpl
{
public:
    virtual int frobnicate(int) const = 0;
};

This interface is required to be stable.

An interface object that proxies to the private implementation. It does not have to use virtual methods. The only allowed member is a pointer to the implementation:

class Frobnicate
{
    std::unique_ptr<IFrobnicateImpl> _impl;
public:
    explicit Frobnicate(std::unique_ptr<IFrobnicateImpl>&& impl = nullptr);
    int frobnicate(int x) const { return _impl->frobnicate(x); }
};

...

Frobnicate::Frobnicate(std::unique_ptr<IFrobnicateImpl>&& impl /* = nullptr */)
: _impl(std::move(impl))
{
    if (!_impl)
        _impl = std::make_unique<DefaultImplementation>();
}

The header file of this class must be stable.

At least one implementation

The Pimpl then buys us a great deal of stability for a library class, at the cost of one heap allocation and additional virtual dispatch.

How does your solution measure up?

It does away with encapsulation. Since your members are protected, any subclass can mess with them.

It does away with interface stability. Whenever you change your data members – and that change is just one refactoring away – you'll have to recompile all dependent code.

It does away with the virtual dispatch layer, preventing easy swapping of the implementation.

So for every objective of the Pimpl pattern, you fail to fulfil this objective. It is therefore not reasonable to call your pattern a variation of the Pimpl, it is much more an ordinary class. Actually, it's worse than an ordinary class because your member variables are private. And because of that cast which is a glaring point of fragility.

Note that the Pimpl pattern is not always optimal – there's a tradeoff between stability and polymorphism on the one hand, and memory compactness on the other. It is semantically impossible for a language to have both (without JIT compilation). So if you're micro-optimizing for memory compactness, clearly the Pimpl is not a suitable solution for your use case. You'll also probably stop using half the standard library, since these awful string and vector classes involve dynamic memory allocations ;-)


答:
Since the data can be considered vectors, vector arithmetic offers a simple solution. This approach has the advantages of either allowing the use of an existing vector library or creating a vector library, which you can then use for other projects.

"Closest" is a question of distance. There are various metrics that give distance between Cartesian vectors, but the most common is the Euclidean, ℓ₂. Euclidean distance can be defined in terms of more basic vector operations.

Start with vector subtraction, which is done component-wise: the difference of vectors is the vector of differences. In a sense, subtraction distributes across vectorization. Symbolically:

```<code><xᵢ> - <yᵢ> = <xᵢ - yᵢ>
</code>```

You also have a componentwise product:

```<code>⃑x * ⃑y = <xᵢ*yᵢ>
</code>```

Next is the dot product (·), which is the sum of the components of the componentwise product:

```<code>⃑x · ⃑y = ∑(⃑x * ⃑y)ᵢ
</code>```

The Euclidean norm (norms in math are abstract length functions) is the square root of the dot product:

```<code>‖⃑x‖ = √(⃑x · ⃑x)
</code>```

Note the Euclidean norm is basically the Pythagorean theorem in n-dimensions, which you can see by expanding operations:

```<code>‖⃑x‖ = √(∑(⃑x * ⃑x)ᵢ) = √(∑(xᵢ²)) = √(x₀²+x₁²+...+x₏²)
</code>```

Finally, the Euclidean distance is the Euclidean norm of the difference:

```<code>ℓ₂(⃑x,⃑y) = ‖⃑x - ⃑y‖
</code>```

Finding the closest vector from a collection is the generic min function: loop over the collection, keeping track of the item (here, vector) with the smallest value (here, distance) seen thus far.

See also the least squares method, which is nearly equivalent but is in terms of functions rather than vectors and omits taking the square-root (which isn't necessary for this particular problem).

Body:
Since the data can be considered vectors, vector arithmetic offers a simple solution. This approach has the advantages of either allowing the use of an existing vector library or creating a vector library, which you can then use for other projects.

"Closest" is a question of distance. There are various metrics that give distance between Cartesian vectors, but the most common is the Euclidean, ℓ₂. Euclidean distance can be defined in terms of more basic vector operations.

Start with vector subtraction, which is done component-wise: the difference of vectors is the vector of differences. In a sense, subtraction distributes across vectorization. Symbolically:

<xᵢ> - <yᵢ> = <xᵢ - yᵢ>

You also have a componentwise product:

⃑x * ⃑y = <xᵢ*yᵢ>

Next is the dot product (·), which is the sum of the components of the componentwise product:

⃑x · ⃑y = ∑(⃑x * ⃑y)ᵢ

The Euclidean norm (norms in math are abstract length functions) is the square root of the dot product:

‖⃑x‖ = √(⃑x · ⃑x)

Note the Euclidean norm is basically the Pythagorean theorem in n-dimensions, which you can see by expanding operations:

‖⃑x‖ = √(∑(⃑x * ⃑x)ᵢ) = √(∑(xᵢ²)) = √(x₀²+x₁²+...+x₏²)

Finally, the Euclidean distance is the Euclidean norm of the difference:

ℓ₂(⃑x,⃑y) = ‖⃑x - ⃑y‖

Finding the closest vector from a collection is the generic min function: loop over the collection, keeping track of the item (here, vector) with the smallest value (here, distance) seen thus far.

See also the least squares method, which is nearly equivalent but is in terms of functions rather than vectors and omits taking the square-root (which isn't necessary for this particular problem).


问:
Crypto hash in 'a href'?
It seems to me that it would be pretty useful to be able to indicate an expected crypto hash value in file downloads especially since so many application and data downloads rely on mirrored hosting. This could be done as an attribute to an 'a' tag (I'm not sure if there is a better way). In this scenario the browser would of course check the hash and probably remove the file with a warning if the hash didn't match what was downloaded. As far as I know there is no way to achieve something like this today. Is that correct? If that's true is there a good reason that something like that shouldn't be proposed as an addition to the HTML5 spec. And finally, if it is a reasonable thing to suggest, what is the best way to make such a suggestion?</p>

答:
Already proposed and being implemented in most major browsers. It's called:

Sub Resource Integrity

Subresource Integrity (SRI) allows specifying the digest of the file that you want to include. The digest is the output of a cryptographic hash function, which helps us achieve integrity.

A nice overview is available here by one of the co-authors of the spec.

Title: Crypto hash in 'a href'?


问:
Separate interface for mutation methods
I've been working on refactoring some code, and I think I may have taken the first step down the rabbit hole. I'm writing the example in Java, but I suppose it could be agnostic.

I have an interface Foo defined as

```<code>public interface Foo {

    int getX();

    int getY();

    int getZ();
}
</code>```

And an implementation as

```<code>public final class DefaultFoo implements Foo {

    public DefaultFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getZ() {
        return z;
    }

    private final int x;
    private final int y;
    private final int z;
}
</code>```

I also have an interface MutableFoo that provides matching mutators

```<code>/**
 * This class extends Foo, because a 'write-only' instance should not
 * be possible and a bit counter-intuitive.
 */
public interface MutableFoo extends Foo {

    void setX(int newX);

    void setY(int newY);

    void setZ(int newZ);
}
</code>```

There are a couple of implementations of MutableFoo that could exist (I haven't implemented them yet). One of them is

```<code>public final class DefaultMutableFoo implements MutableFoo {

    /**
     * A DefaultMutableFoo is not conceptually constructed
     * without all values being set.
     */
    public DefaultMutableFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public void setX(int newX) {
        this.x = newX;
    }

    public int getY() {
        return y;
    }

    public void setY(int newY) {
        this.y = newY;
    }

    public int getZ() {
        return z;
    }

    public void setZ(int newZ) {
        this.z = newZ;
    }

    private int x;
    private int y;
    private int z;
}
</code>```

The reason I have split these is because it is equally likely for each to be used. Meaning, it is equally likely that someone using these classes will want an immutable instance, as it is they will want a mutable one.

The primary use-case that I have is an interface called StatSet that represents certain combat details for a game (hitpoints, attack, defense). However, the "effective" stats, or the actual stats, are a result of the base stats, that can never be changed, and the trained stats, which can be increased. These two are related by

```<code>/**
 * The EffectiveStats can never be modified independently of either the baseStats
 * or trained stats. As such, this StatSet must never provide mutators.
 */
public StatSet calculateEffectiveStats() {
    int effectiveHitpoints =
        baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    int effectiveAttack =
        baseStats.getAttack() + (trainedStats.getAttack() / 4);
    int effectiveDefense =
        baseStats.getDefense() + (trainedStats.getDefense() / 4);

    return StatSetFactory.createImmutableStatSet(effectiveHitpoints, effectiveAttack, effectiveDefense);
}
</code>```

the trainedStats are increased after every battle like

```<code>public void grantExperience() {
    int hitpointsReward = 0;
    int attackReward = 0;
    int defenseReward = 0;

    final StatSet enemyStats = enemy.getEffectiveStats();
    final StatSet currentStats = player.getEffectiveStats();
    if (enemyStats.getHitpoints() >= currentStats.getHitpoints()) {
        hitpointsReward++;
    }
    if (enemyStats.getAttack() >= currentStats.getAttack()) {
        attackReward++;
    }
    if (enemyStats.getDefense() >= currentStats.getDefense()) {
        defenseReward++;
    }

    final MutableStatSet trainedStats = player.getTrainedStats();
    trainedStats.increaseHitpoints(hitpointsReward);
    trainedStats.increaseAttack(attackReward);
    trainedStats.increaseDefense(defenseReward);
}
</code>```

but they aren't increased just after battle. Using certain items, employing certain tactics, clever use of the battlefield all can grant different experience.

Now for my questions:

Is there a name for splitting interfaces by accessors and mutators into separate interfaces?

Is splitting them in this way the 'right' approach if they are equally likely to be used, or is there a different, more accepted pattern that I should use instead (eg. Foo foo = FooFactory.createImmutableFoo(); which could return DefaultFoo or DefaultMutableFoo but is hidden because createImmutableFoo returns Foo)?

Are there any immediately foreseeable downsides to using this pattern, save for complicating the interface hierarchy?

The reason I started designing it this way is because I'm of the mindset that all implementers of an interface should adhere to the simplest interface possible, and provide nothing more. By adding setters to the interface, now the effective stats can be modified independently of its parts.

Making a new class for the EffectiveStatSet does not make much sense as we're not extending the functionality in any way. We could change the implementation, and make an EffectiveStatSet a composite of two different StatSets, but I feel that is not the right solution;

```<code>public class EffectiveStatSet implements StatSet {

    public EffectiveStatSet(StatSet baseStats, StatSet trainedStats) {
        // ...
    }

    public int getHitpoints() {
        return baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    }
}
</code>```

答:
Wow... this really takes me back.  I tried this same idea a few times.  I was too stubborn to give up on it because I thought there would be something good to learn.  I have seen others try this in code too.  Most implementations I have seen called the Read-Only interfaces like yours FooViewer or ReadOnlyFoo and the Write-Only interface the FooEditor or WriteableFoo or in Java I think I saw FooMutator once.  I'm not sure there is an official or even common vocabulary for doing things this way.

This never did anything useful for me in the places I tried it.  I would avoid it altogether.  I would do as others are suggesting and take a step back and consider whether you really need this notion in your bigger idea.  I'm not sure there is a right way to do this since I never actually kept any of the code I produced while trying this.  Each time I backed out after considerable effort and simplified things.  And by that I mean something along the lines of what others said about YAGNI and KISS and DRY.

One possible downside: repetition.  You will have to create these interfaces for a lot of classes potentially and even for just one class you have to name each method and describe each signature at least twice.  Of all the things that burn me in coding, having to change multiple files in this way gets me in the most trouble.  I eventually end up forgetting to make the changes in one place or the other.  Once you have a class called Foo and interfaces called FooViewer and FooEditor, if you decide it would be better if you called it Bar instead you have to refactor->rename thrice unless you have a really amazingly smart IDE.  I even found this to be the case when I had a considerable amount of the code coming from a code generator.

Personally, I dislike creating interfaces for things that have only a single implementation too.  It means when I travel around in the code I can't just jump to the only implementation directly, I have to jump to the interface and then to the implementation of the interface or at least press a few extra keys to get there.  Those things add up.

And then there is the complication you mentioned.  I doubt I'll ever go this particular way with my code again.  Even for the place this fit best into my overall plan for the code (an ORM I built) I pulled this and replaced it with something easier to code with.

I would really give more thought to the composition you mentioned.  I'm curious why you feel that would be a bad idea.  I would have expected to have EffectiveStats compose and immutable Stats and something like StatModifiers which would further compose some set of StatModifiers that represent whatever might modify stats (temporary effects, items, location in some enhancement area, fatigue) but that your EffectiveStats would not need to understand because StatModifiers would manage what those things were and how much effect and what kind they would have on which stats.  The StatModifier would be an interface for the different things and could know things like "am I in the zone", "when does the medicine wear off", etc... but would not have to even let any other objects know such things.  It would only need to say which stat and how modified it was right now.  Better yet StatModifier could simply expose a method for producing a new immutable Stats based on another Stats which would be different because it had been altered appropriately.  You could then do something like currentStats = statModifier2.modify(statModifier1.modify(baseStats)) and all the Stats can be immutable.  I wouldn't even code that directly, I would probably loop through all the modifiers and apply each to the result of the previous modifiers starting with baseStats.

Title: Separate interface for mutation methods


答:
To me, the advantages don't outweigh the disadvantages.

Advantages:

It can speed up compilation, since it saves a rebuild if only the private method signatures have changed. But rebuilding is necessary if public or protected method signatures or private data members have changed, and it's rare that I have to change private method signatures without touching any of these other options.

It can permit more aggressive compiler optimizations, but LTO should permit many of the same optimizations (at least, I think it can - I'm not a compiler optimization guru), plus some more besides, and can be made standard and automatic.

Disadvantages:

You mentioned a couple of disadvantages: the inability to use private, and complexities with templates. To me, though, the biggest disadvantage is that it's simply awkward: an unconventional programming style, with not-quite-standard pimpl-style jumps between interface and implementation, which will be unfamiliar to any future maintainers or new team members, and which may be poorly supported by tooling (see, e.g., this GDB bug).

The standard concerns about optimization apply here: Have you measured that the optimizations give a meaningful improvement to your performance? Would your performance be better by doing this or by taking the time it would take to maintain this and invest it in profiling hotspots, improving algorithms, etc.? Personally, I'd rather pick a clear and straightforward programming style, on the assumption that it will free up time to do targeted optimizations. But that's my perspective for the kinds of code I work on - for your problem domain, the tradeoffs may be different.

Side note: Permitting private with method-only pimpl

You asked about how to permit private members with your method-only pimpl suggestion. Unfortunately, I consider method-only pimpl to be kind of a hack, but if you've decided that the advantages outweigh the disadvantages, then you might as well embrace the hack.

A.h:

```<code>#ifndef A_impl
#define A_impl private
#endif

class A
{
public:
    A();
    void DoSomething();
A_impl:
    int mData1;
    int mData2;
};
</code>```

A.cpp:

```<code>#define A_impl public
#include "A.h"
</code>```

Title: Can a pimpl variation be implemented without any performance penalty?

Body:
One of the issues of pimpl is the performance penalty of using it (additional memory allocation, non-contiguous data members, additional indirections, etc..). I would like to propose a variation on the pimpl idiom that will avoid these performance penalties at the expense of not getting all the benefits of pimpl. The idea is to leave all private data members in the class itself and move only the private methods to the pimpl class.
The benefit compared to basic pimpl is that the memory remains contiguous (no additional indirection). The benefits compared to not using pimpl at all are:

It hides the private functions.

You can structure it so that all these functions will have internal linkage and allow the compiler to more aggressively optimize it.

So my idea is to make the pimpl inherit from the class itself (sounds a bit crazy I know, but bear with me).
It would look something like this:

In A.h file:

```<code>class A
{
    A();
    void DoSomething();
protected:  //All private stuff have to be protected now
    int mData1;
    int mData2;
//Not even a mention of a PImpl in the header file :)
};
</code>```

In A.cpp file:

```<code>#define PCALL (static_cast<PImpl*>(this))

namespace //anonymous - guarantees internal linkage
{
struct PImpl : public A
{
    static_assert(sizeof(PImpl) == sizeof(A),
                  "Adding data members to PImpl - not allowed!");
    void DoSomething1();
    void DoSomething2();
    //No data members, just functions!
};

void PImpl::DoSomething1()
{
    mData1 = bar(mData2); //No Problem: PImpl sees A's members as it's own
    DoSomething2();
}

void PImpl::DoSomething2()
{
    mData2 = baz();
}

}
A::A(){}

void A::DoSomething()
{
    mData2 = foo();
    PCALL->DoSomething1(); //No additional indirection, everything can be completely inlined
}
</code>```

As far as I see there are absolutely no performance penalties in using this vs no pimpl and some possible performance gains and cleaner header file interface. One disadvantage this has vs standard pimpl is that you can't hide the data members so changes to those data members will still trigger a recompilation of everything that depends on the header file. But the way I see it, it's either get that benefit or the performance benefit of having the members contiguous in memory (or do this hack - "Why Attempt #3 is Deplorable"). Another caveat is that if A is a templated class the syntax gets annoying (you know, you can't use mData1 directly, you need to do this->mData1, and you need to start using the typename and maybe template keywords for dependent types and templated types, etc.). Yet another caveat is that you can no longer use private in the original class, only protected members, so you can't restrict access from any inheriting class, no just the pimpl. I tried but couldn't get around this issue. For example, I tried making the pimpl a friend template class in the hopes of making the friend declaration broad enough to allow me to define the actual pimpl class in an anonymous namespace, but that just doesn't work. If anyone has any idea of how to keep the data members private and still allow an inheriting pimpl class defined in an anonymous namepsace to access those, I'd really like to see it! That would eliminate my main reservation from using this.

I feel though, that these caveats are acceptable for the benefits of what I propose.

I tried looking online for some reference to this "function-only pimpl" idiom but couldn't find anything. I'm really interested in what people think about this. Are there other issues with this or reasons I shouldn't use this?

UPDATE:

I've found this proposal that more or less tries to accomplish exactly what I am, but doing so by changing the standard. I completely agree with that proposal and hope it will make it into the standard (I know nothing of that process so I have no idea of how likely that's to happen). I'd much rather have it possible to do this through a built in language mechanism. The proposal also explains the benefits of what I'm trying to achieve much better than me. It also doesn't have the issue of breaking encapsulation like my suggestion has (private -> protected). Still, until that proposal makes it into the standard (if that ever happens), I think my suggestion makes it possible to get those benefits, with the caveats I listed.

UPDATE2:

One of the answers mentions LTO as a possible alternative to getting some of the benefits (more aggressive optimizations I'm guessing). I'm not really sure exactly what goes on in various compiler optimization passes but I do have a bit of experience with the resulting code (I use gcc). Simply putting the private methods in the original class will force those to have external linkage.

I might be wrong here, but the way I interpret that is that the compile-time optimizer cannot eliminate the function even if all its call instances are completely inlined inside that TU. For some reason even LTO refuses to get rid of the function definition even if it seems that all the call instances in the entire linked binary are all inlined. I found some references stating that it's because the linker doesn't know if you'll somehow still call the function using function pointers (though I don't understand why the linker can't figure out that the address of that method is never taken).

This is not the case if you use my suggestion and put those private methods in a pimpl inside an anonymous namespace. If those get inlined, the functions will NOT appear in (with -O3, that includes -finline-functions) the object file.

The way I understand it, the optimizer, when deciding whether or not to inline a function, takes into account its impact on code size. So, using my suggestion I'm making it slightly "cheaper" for the optimizer to inline those private methods.

Body:
To me, the advantages don't outweigh the disadvantages.

Advantages:

It can speed up compilation, since it saves a rebuild if only the private method signatures have changed. But rebuilding is necessary if public or protected method signatures or private data members have changed, and it's rare that I have to change private method signatures without touching any of these other options.

It can permit more aggressive compiler optimizations, but LTO should permit many of the same optimizations (at least, I think it can - I'm not a compiler optimization guru), plus some more besides, and can be made standard and automatic.

Disadvantages:

You mentioned a couple of disadvantages: the inability to use private, and complexities with templates. To me, though, the biggest disadvantage is that it's simply awkward: an unconventional programming style, with not-quite-standard pimpl-style jumps between interface and implementation, which will be unfamiliar to any future maintainers or new team members, and which may be poorly supported by tooling (see, e.g., this GDB bug).

The standard concerns about optimization apply here: Have you measured that the optimizations give a meaningful improvement to your performance? Would your performance be better by doing this or by taking the time it would take to maintain this and invest it in profiling hotspots, improving algorithms, etc.? Personally, I'd rather pick a clear and straightforward programming style, on the assumption that it will free up time to do targeted optimizations. But that's my perspective for the kinds of code I work on - for your problem domain, the tradeoffs may be different.

Side note: Permitting private with method-only pimpl

You asked about how to permit private members with your method-only pimpl suggestion. Unfortunately, I consider method-only pimpl to be kind of a hack, but if you've decided that the advantages outweigh the disadvantages, then you might as well embrace the hack.

A.h:

#ifndef A_impl
#define A_impl private
#endif

class A
{
public:
    A();
    void DoSomething();
A_impl:
    int mData1;
    int mData2;
};

A.cpp:

#define A_impl public
#include "A.h"


问:
Correct approach for creating api contract
I am trying to design an API. For creating contracts below are the two approaches:

Approach 1:

```<code>public class MyController
{
  public void MyAction1(Dictionary<string, dynamic> input)
  {
    //Use input like below
    //Read from input dictionary and apply minimal business logic if needed
    //And Call CustomDataProvider library with input object itself(DataProvider designed in such a way that it takes Dictionary and used values as procedure input. Dictionary key is same as procedure arguments.)
  }

  public void MyAction2(Dictionary<string, dynamic> input)
  {
    //Use input like below
    //Read from input dictionary and apply minimal business logic if needed
    //And Call CustomDataProvider library with input object itself(DataProvider designed in such a way that it takes Dictionary and used values as procedure input. Dictionary key is same as procedure arguments.)
  }
}
</code>```

In this case we don't need data contract at all.

Approach 2:

```<code>public class MyController
{
    public void MyAction1(MyContractBusinessObject1 input)
    {
        //Do normal business logic processing using input object and call DBProvider by creating a dictionary from business object
    }
    public void MyAction2(MyContractBusinessObject2 input)
    {
        //Do normal business logic processing using input object and call DBProvider by creating a dictionary from business object
    }
}
</code>```

In this case we'll have different business classes as contract for different action inputs. Which of the above approaches is better and why?

Let me give an example. Suppose My actions are doing login and new account creation. In first case input will be

```<code>new Dictionary<string, dynamic>{
    {"Name","myname"},
    {"Passowrd",'mypassword'}
}

new Dictionary<string, dynamic>{
    {"Name","myname"},
    {"Passowrd",'mypassword'},
    {"Age",myage},
    {"otherInfo",myotherinfo}
}
</code>```

but in approach 2 input will be

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

class NewAccount{
    public string Name{get; set;}
    public string Password{get; set;}
    public int Age{get; set;}
    public OtherInfo OtherInfo{get; set;}
}
</code>```

答:
I generally grumble about both approaches.  If I had to choose between only those two choices I would probably pick the fully typed one because it will tell me more about what I am required to provide just by looking at the method signature and argument types.  The Dictionary solution requires me to go look at API documentation or worse yet the implementation's code to find out what values are meaningful or required in the dictionary.  The thing is, you do have a data contract of some kind no matter which method you choose.  The difference is how discoverable that contract is.

I am a big believer in making things as easy as possible if you are providing an API.  If the set of things you are required to pass to the API is small for each method it is actually often easier to code against an API when all required values are passed separately like:  controller.Login(myname, mypassword) or
controller.NewAccount(myname, mypassword, myage, myotherinfo).  Then I can tell from just the method signature what I am expected to pass.  Some of the fanciest IDEs will even autofill the values if there are reasonable values in the calling context to guess.  I would only bundle up the arguments into a structure of some kind if that structure is complex or if it gets used all over the API for various things.

OwnerDisplayName: Ashutosh Pandey


答:
No, you can't implement it without a performance penalty. PIMPL is, by it's very nature, a performance penalty, as you are applying a run-time indirection.

Of course, this depends on exactly what you wanted to indirect. Some information is simply not used by the consumer- like what exactly you intend to put in your 64 4-byte-aligned bytes. But other information is- like the fact that you want 64 4-byte-aligned bytes for your object.

Generic PIMPLs without performance penalties do not exist and will never exist. It's the same information that you deny to your user that they want to use to optimize. If you give it to them, your IMPL is not abstracted; if you deny it to them, they can't optimize. You can't have it both ways.


问:
MVVM in Photoshop-like application: What object has the responsibility for composing the document?
I'm wondering how an application like Adobe Photoshop, could be architectured to conform to the C+M+V+VM design-pattern, specifically how do you handle the canvas?

There would be a Model system which represents the current document, with its layers (each containing raw pixel data, potentially gigabytes worth), effects applied to layers, and other information about the document state.

Then you would have the ViewModel for the Main Window which would have child-ViewModels for each tool-window, as well as a child-ViewModel for the main canvas area. My question relates to how the ViewModel would represent the current canvas data. It is the View's responsibility to draw the pixels of the composited document to the screen (or some virtual output device for tests), but who has responsibility to compose the document? Is it correct to even compose the document at all? - especially if the View is particularly advanced enough to have the capability to do that itself, such as hardware-accelerated Views. What if composition is done at the ViewModel layer on the GPU, the data would have to be passed back into main-memory and then copied again to the GPU for the View - the optimization of keeping the data in GPU memory cannot happen because the View and ViewModel should be ignorant of each other.

Is there a solution to this problem, or would a different design-pattern be appropriate?

答:
There is something I had to learn while designing medical imaging / data visualization software in WPF/MVVM:

If your domain model deals with visualization, then your ViewModel has to contain visual information.

I'll elaborate.

Let's take an example of an accounting system. There you can get every application functionality purely in the model, but it would be weird for an human to deal with all the accounting concepts without visualizing them.
Enter the View, purely as an aid (a true Graphical User Interface in a Human-Computer-Interaction sense), so the human operator can see the state of the underlying information, which has not a visual by itself.

On the other hand, let's take your extreme example: an application whose very purpose is to manipulate images. That is, the core Domain Model class is the Composite Image, with its layers, and each one with its pixel effects, and masks, and so on.

One core concept of MVVM, Data Binding totally loses its sense here: how are you suppose to have a property in the ViewModel, which is bound to a property in the View, if the very thing you are representing is already composed of pixels? At least, I suppose, your code-behind would need to be very rich (instead of non-existant in purist by-the-book MVVM).

What I have been doing lately (the current application I am developing has a custom realtime plotter) is more or less like this:

My Model layer is a Domain Model, containing only the conceptual classes related to the broad problem, and the rules by which the objects cooperate with one another. Nothing application-related (that is, which might vary between different applications working on the same domain) lives in this layer, which by the way does not contain WPF infrastructure. Good class candidates would be CompositeCanvas, CanvasLayer, PixelEffect, Mask, Tool, etc.

The ViewModel layer would contain application logic, that is, how the current application chooses to manipulate the domain model objects. Here we start to use WPF related classes. For example, I most probably would represent a CompositeCanvas with a WriteableBitmap, since it can be directly used as the Source property of an Image control via classic Data Binding.

The View layer would be the dumbest as possible. Apart from the skinned input controls (toolbar buttons, custom mouse cursors and manipulator handlers), the actual CompositeImage would be composed of one or more WriteableBitmaps stacked into a Canvas or Grid or ViewBox (or a combination of them).

One important thing to consider is how the layers interact to each other:

If you have independent layers which don't interact with one another - that is, an application less sophisticated than Photoshop - then you can composite in the View, stacking multiple Image controls over one another inside a grid.

Now if you want to implement blending modes, you might prefer to have a single Image to represent every layer, and apply the composition to its BitmapSource, which might be a DrawingImage with a DrawingGroup containing multiple ImageDrawing, one for each layer. That transfer the compositing to the ViewModel.

Now if you want full control, so that you can apply sophisticated image-processing algorithms, represent your image as arrays (of double, that would be a good thing), change color modes, and do other Clever Things, then you could perfectly has your layers represented in the model, and have some operation to, say, transfer that array to a WriteableBitmap in the ViewModel, which then automatically updates the View's Image.

It is interesting to "visualize" (pun intended) how, for example, drawing with a self-smoothing, brushed pencil would work: with the selected tool, you click on the image and drag. You could implement your DataContext (ViewModel) as an Interface, say ITool and make mouse events like MouseMove call methods on the ViewModel. You would then store the drawing-space (not screen-space) coordinates in an array, which could be continuously smoothed by some algorithm defined in the model. Then, you can regenerate your image source (that is, render it in the model), and in the ViewModel you just set its result to the CanvasSource property, and the property changed event would automatically update the View. This is quite different than most mouse-drawing demos found using WPF.

Hope this helps!


问:
Performance of sharing single object with multiple threads in Java
In Java, if I create an object that has a method to do something, and I pass that object to multiple threads which call the method, is there a performance difference from creating an individual instance of that class in each thread?

In other words, does it cause a bottleneck for thousands of threads to be trying to access the same object's methods at the same time?

I don't know a ton about memory or how a processor works, but it seems to me that the single object option would have a single instance in memory, and thousands of threads could be trying to utilize that code at once.  With a single core processor, this might be irrelevant since the processor can only be doing one thing.  But in a multi-core setup, could multiple threads all utilize the code of a single object in memory at the same time?

答:
It depends.

Without any synchronisation and without volatile or atomic variables it does not make a difference.

However, if those methods change the object-state you will need some form of synchronisation, otherwise multiple threads would overwrite changes from other threads or just not see the change. Synchronisation is not free, volatile variables and atomics are not free, so if you use one of them, it makes a difference, yes.


问:
Can I listen on a port without interrupting traffic?
I have developed the bare bones on a socket server in Python. I'm trying to capture the HTTP packets going to a web server without blocking them.

```<code>    try:
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind(('0.0.0.0', configuration.get('port')))
    except OSError as OE:
        logging.report("That port appears to be in use.")
</code>```

The problem is, the machine I'm running it has a webserver bound on 80.

Is it possible to listen on a port without blocking other applications or interfering with them?

答:
The functionality for that is located in the pcap API. The implementation of that is in library libpcap for Unix/Linux and library Winpcap for Windows.

There are Python wrappers, e.g. pypcap, to access those libraries.

Depending on your system, you might need 'elevated privileges' (root/administrator) to gain access to packet data.

Wireshark is built on top of these libraries.


问:
What was the reason for the creation of boolean variables?
I found out that some languages like C don't have support for boolean variables and programmers use integers with values of 0 and 1 instead. Is there any specific reason why some languages moved away from this other than improved readability?</p>

答:
The main reasons are:

1. Use cases for booleans are extremely common.

I'll assume the well-known convention that 0 means false and 1 means true is enough proof of this.

2. We want type safety.

An integer can do everything that a boolean can, and a lot more, so it's not like we were missing any functionality.

But, if we used integers to represent booleans, then our "booleans" would be able to do things that booleans shouldn't be able to do (such as addition and subtraction), and they'd be able to interact with "real integers" in ways that don't make any sense (strictly speaking, true should not be equal to 1).

We usually use the term "type safety" to refer to issues like this. Using integers to represent booleans is not a "type-safe" solution.

Type safety is generally considered a very good thing, especially in statically typed languages where the compiler is effectively checking your program for type errors on every compilation. Given that true == 42 is not a valid or meaningful comparison, it would be nice if the compiler simply did not allow it and forced us to go fix that piece of code. The "improved readability" you mention in your question is another typical benefit.

3. A user-defined type (i.e., a class or struct) cannot represent a boolean correctly, so it would have to be a primitive or built-in type

For many of us, this is the really interesting and non-obvious part. In the case of C++, this issue is explained quite thoroughly by Herb Sutter's Guru of the Week #26. I'll quote his summary here:

A typedef ... bool wouldn't allow overloading on bool.

A #define bool wouldn't allow overloading either and would wreak the
  usual havoc of #defines.

An enum bool would allow overloading but couldn't be automatically
  converted from a conditional expression (as in "b = (i == j);").

A class bool would allow overloading but wouldn't let a bool object be
  tested in conditions (as in "if( b )") unless it provided an automatic
  conversion to something like int or void*, which would wreak the usual
  havoc of automatic conversions.

Yes, we really did need a builtin bool! And, finally, there's one more
  thing (related to overloading) that we couldn't have done otherwise,
  either, except perhaps with [a class]: specify that conditional
  expressions have type bool.

So C++ can't do non-primitive booleans. At the risk of oversimplifying the differences between langauges, if you can't do something in C++, there's a good chance you can't do it in any of the other mainstream OOP langauges. I believe the C# implementation would get exactly as close as the C++ one, but no closer, and Java would be significantly worse off since it deliberately doesn't offer operator overloading or implicit conversions.


问:
How to make a large codebase easier to understand
Suppose that I am developing a relatively large project. I have already documented all my classes and functions with Doxygen, however, I had an idea to put a "programmer's notes" on each source code file.

The idea behind this is to explain in layman's terms how a specific class works (and not only why as most comments do). In other words, to give fellow programmers an other-view of how a class works.

For example:

```<code>/*
 * PROGRAMMER'S NOTES:
 *
 * As stated in the documentation, the GamepadManager class
 * reads joystick joystick input using SDL and 'parses' SDL events to
 * Qt signals.
 *
 * Most of the code here is about goofing around the joystick mappings.
 * We want to avoid having different joystick behaviours between
 * operating systems to have a more integrated user experience, since
 * we don't want team members to have a bad surprise while
 * driving their robots with different laptops.
 *
 * Unfortunately, we cannot use SDL's GamepadAPI because the robots
 * are interested in getting the button/axes numbers, not the "A" or
 * "X" button.
 *
 * To get around this issue, we created a INI file for the most common
 * controllers that maps each joystick button/axis to the "standard"
 * buttons and axes used by most teams.
 *
 * We choose to use INI files because we can safely use QSettings
 * to read its values and we don't have to worry about having to use
 * third-party tools to read other formats.
 */
</code>```

Would this be a good way to make a large project easier for new programmers/contributors to understand how it works? Aside from maintaining a consistent coding style and 'standard' directory organization, are there any 'standards' or recommendations for these cases?

答:
Similar to what @meriton said, break the code down into separate components. Even better, break down the codebase into separate packages (JARs, gems, eggs, whatever) to make it even more clear how the components are separated. If there is a bug, a developer only needs to find the package where the bug is, and (hopefully) only fix it there. Not to mention, it's easier to do unit testing, and you get to take advantage of dependency management.

Another solution: make the codebase smaller. The less code there is, the easier it is to understand. Refactor out unused or duplicated code. Use declarative programming techniques. This takes effort, of course, and often isn't possible or practical. But it's a worthy goal. As Jeff Atwood has written: The Best Code Is No Code At All


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
Visible side-effects in unexpected places.

In .Net, examples would be ToString(), Equals() / GetHashCode(), property getters, and implicit conversions.

(To be clear, I'm talking about something more than lazy instantiation or logging code)

```<code>throw new Exception(ex.Message);
</code>```

Explanation

Title: Is anything in programming truly evil?

Body:
Visible side-effects in unexpected places.

In .Net, examples would be ToString(), Equals() / GetHashCode(), property getters, and implicit conversions.

(To be clear, I'm talking about something more than lazy instantiation or logging code)

throw new Exception(ex.Message);

Explanation


问:
Most useful features of VIM that aren't standard in a IDE
I'm considering whether I should start using VIM again instead of an IDE. What are the most useful features of VIM that aren't standard in an IDE?</p>

答:
Did you know that there is a vi plugin for eclipse? It costs 15 euro (20ish US$) but it is so worth. No more dd in the middle of a document, and missing all the tiny useful things.

Perhaps a bit off topic but I thought it was worth pointing out.


问:
The Programmers Bill of Responsibilities
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?

答:
The programmer should know and use the core libraries and platform used.

Specially when the programmer comes from other platform/language. Is terrible to find the programmer struggling for something the core library provide or to misuse the platform advantage due to ignorance.

The programmer should create self documenting code

It's very important to have the code documented for other to use, but when it comes to maintainability, self documenting code may literally save hours and hours of frustration.

For instance compare:

```<code>// validates if is leap year
if(  year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) ) {
     doSomethingWithFebruary();
}
</code>```

to

```<code>if( isLeapYear( year ) ) {
    doSomethingWithFebruary();
}
</code>```

Body:
The programmer should know and use the core libraries and platform used.

Specially when the programmer comes from other platform/language. Is terrible to find the programmer struggling for something the core library provide or to misuse the platform advantage due to ignorance.

The programmer should create self documenting code

It's very important to have the code documented for other to use, but when it comes to maintainability, self documenting code may literally save hours and hours of frustration.

For instance compare:

// validates if is leap year
if(  year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) ) {
     doSomethingWithFebruary();
}

to

if( isLeapYear( year ) ) {
    doSomethingWithFebruary();
}


问:
How do you share your craft with non programmers?
Sometimes I feel like a musician who can't play live shows. Programming is a pretty cool skill, and a very broad world, but a lot of it happens "off camera"- in your head, in your office, away from spectators.

You can of course talk about programming with other programmers, and there is peer programming, and you do get to create something that you can show to people, but when it comes to explaining to non programmers what is it that you do, or how was your day at work, it's sort of tricky.

How do you get the non programmers in your life to understand what is it that you do?

NOTE: this is not a repeat of Getting non-programmers to understand the development process, because that question was about managing client expectations.

答:
Metaphors

A lot of times, I don't describe it as a program at all, I try to represent it as a completely different concept with similar interrelationships.

It makes visualizing the program a lot more interesting and sometimes it helps me look at it in a new light.

You don't describe electricity to someone who has never worked with it before by talking about current and voltages do you? Plus, it's fun to describe some concepts as if some ultra aware computer process makes them happen as if by means of magic. A little story imagination doesn't hurt them as the reality of how cold and rational computers really are.


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
Yes.

If you're looking for executable efficiency, you're down to C or C++, so I'll focus on that.

Even before templates were common, I preferred using C++ over C for the kinds of executables you discuss as early as the mid 1990s for two very simple reasons: object polymorphism and RAII.

I've used polymorphic C++ objects for all kinds of interesting things. For instance, I was working on an embedded Linux system with frame buffer overlays on OMAP and XScale ARM CPUs. The two hardware architectures have different overlay features with very different APIs. I used a common virtual "Overlay" base class to expose an idealized view of overlays, and then wrote "OmapOverlay" and "XScaleOverlay" classes which were instantiated appropriately at runtime, depending on which architecture the code detected it was running on.

To oversimplify, RAII is the idea that you allocate resources connected to an object during the object's constructor, or maybe later on in the object's lifetime, and the resources get deallocated or released in the object's destructor. That's really nice in C++, because objects which are automatic variables are destructed when they go out of scope. For someone who's equally competent in C and C++, it's far easier to avoid resource and memory leaks in C++. You also don't see much C++ code with the very common C meme of a label at the end of a function preceding a bunch of calls to free(), and various goto's in the function block jumping there.

I'm fully aware that you can do all these things with C - it's just a lot more work, way more lines of code, and what you wind up with is a lot uglier and often harder to understand. There's polymorphism code all through the X server internals, and man, is it fugly and weird and frequently hard to trace through.

I also do a lot of work with GNOME technologies like GTK+ and Clutter, all of which are written in C using the GObject system. GObject is like the C++ object system with the nice cover taken off and all the ugly internals exposed, and it usually requires a half-dozen lines of code to do what a one-line C++ method call would do. I'm currently writing some ClutterActors, and while the math is really interesting, I'm constantly thinking, "This would all be so much more succinct and comprehensible in C++".

I also often think, "You know, if I were writing this in C++ instead of C, I'd be out in the living room watching MythBusters with my wife instead of sitting in my office at 9 PM."


问:
How to find a programming mentor?
I decided to learn programming. I've been reading SO for few days, and I think I will start with C++, as I read some articles. I am aware of loops, arrays, program logic and objects a little and I need someone to look me over and help me with small questions I get when doing my first projects.

So here is the question - where do I find such guy? I don't got any friends who program and all.

EDIT: 2 years later, I am still looking for mentor. I did not actively code just started 3 months again. I work on Objective-C and iOS programming and game programming with Cocos2d. If you want to become my mentor, drop me a or comment.

答:
To find a mentor, don't look for a mentor.  Try to improve yourself in specific ways.  If you work hard enough at getting better, you will both find that you come in contact with like-minded folks, and find that you have something in common with those people.

Users groups are the likely place to find a mentor, but no one wants to help someone that is there thinking "I'm looking for a mentor."  But if you are there thinking: "I'd love it if someone could help me learn to write good JavaScript unit tests," or "I'd love to pair with someone and test-drive a kata in Clojure," sooner or later you will find someone that shares your interests and is a little farther along.

Title: How to find a programming mentor?


问:
How often do you run & test your code while programming?
Especially when writing new code from scratch in C, I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head. Don't get me wrong - I wouldn't write 1000 lines without testing at all (that would be gambling), but I would write a whole subroutine and test it (and fix it if necessary) after I think I'm finished.

On the other side, I've seen mostly newbies that run & test their code after every line they enter in the editor and think that debuggers can be a substitute for carefulness and sanity. I consider this to be a lot of distraction once you've learned the language syntax.

What do you think is the right balance between the two approaches? Of course the first one requires more experience, but does it affect productivity positively or negatively? Does the second one help you spot errors at a finer level?

答:
Personally, I must work in small chunks because I am not smart enough to keep hours worth of coding in my biological L1 cache. Because of my limited capabilities, I write small, cohesive methods and design objects to have very loose coupling. More powerful tools and languages make it easier to code longer without building, but there is still a limit for me.

My preference is to write a small piece, verify that it works as I expect. Then, in theory, I am free to forget about the details of that piece and treat it as a black box as much possible.


答:
A programmer has the responsibility to respect the system his program will be running on.  After development and testing is finished, the program will be deployed to be used for its intended purpose, and that usually involves other people running it on their computers.  The programmer needs to keep this in mind: his program is running on someone else's property, not their own, and needs to behave itself as a guest in their home instead of barging in like it owns the place.

For example, his program should not:

change global settings without the user's consent. (Including shared library management issues.)

delete or modify data that belongs to the user or to another program without the user's consent.

update itself without the user's consent.

make itself difficult to uninstall.

make itself difficult to shut down.

disable itself or interfere in any way with proper functioning of the computer if the program is unable to pass some fallible license check.

assume that it is the only significant program running on the system and hog system resources accordingly. (Exceptions can be made for actual single-tasking machines, of course, or for programs that the user could be reasonably expected to run alone, such as heavy fullscreen games.)

jump out in front of the user with a popup window while the user is doing other things in other programs.  (I'm looking at you, Yahoo Messenger!)

Title: The Programmers Bill of Responsibilities

Body:
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?


答:
How often I run and test code depends on what language I'm working with at the time. If I'm coding a stored procedure, I'll usually wait until everything's there.

On the other hand, if I'm coding in Lisp, I'll try each function after I type it in.

If I'm coding in Haskell, I'll typically do a compile after each function to catch any type errors, and run the code after everything's done.

Title: How often do you run & test your code while programming?

Body:
Especially when writing new code from scratch in C, I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head. Don't get me wrong - I wouldn't write 1000 lines without testing at all (that would be gambling), but I would write a whole subroutine and test it (and fix it if necessary) after I think I'm finished.

On the other side, I've seen mostly newbies that run & test their code after every line they enter in the editor and think that debuggers can be a substitute for carefulness and sanity. I consider this to be a lot of distraction once you've learned the language syntax.

What do you think is the right balance between the two approaches? Of course the first one requires more experience, but does it affect productivity positively or negatively? Does the second one help you spot errors at a finer level?


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答:
I try to write "clean code" in the Bob Martin sense (e.g. OO design). There is great value in writing clean code. It is much more maintainable.

Then I let ReSharper make it "pretty code" for me (e.g. alignment, line breaks, etc.). There is good value in writing pretty code. But there are diminishing returns. Some prettification makes it a bit more maintainable due to ease of reading.

If you feel that neatly lining up huge blocks of code is necessary to make it readable, then the problem is your freakin huge block of code! It's too big. I see many examples of people taking great pains to prettify some very poorly designed code.

If I didn't have ReSharper, I would still have clean code, but it wouldn't be quite as pretty.

I don't think I should spend more than ~5% of my coding time in prettifying. Which means the more powerful my editor and the more proficient I am with it, the more prettification I can do.

Title: Do you actually write 'clean code'?


问:
Is there any evidence that one of the current alternate JVM languages might catch on?
There's been a lot of enthusiasm about JRuby, Jython, Groovy, and now Scala and Clojure as the language to be the successor to Java on the JVM.

But currently only Groovy and Scala are in the TIOBE top 100, and none are in the top 50.  Is there any reason to think that any of this bunch will ever gain significant adoption?

My question is not primarily about TIOBE, but about any evidence that you might see that could indicate that one of these languages could get significant backing that goes beyond the enthusiasts.

答:
I can remember when Perl, Python and Ruby didn't have any significant backing beyond the enthusiasts, and I'm not sure anyone could have predicted their success.

On the other hand, good things tend to happen once you get enough enthusiasts. Libraries get written and polished, and so does documentation. Over time, the language becomes "batteries included" because the army of enthusiasts codes up everything they happen to need.

Only time will tell if what happened with Perl, Python and Ruby will happen to the JVM languages. The ability to predict such a thing would probably be better applied to the stock market.


答:
I like to write my test before I write my implementation code.  I like this for three reasons:

Writing my test code before hand helps me think through how my code should be used.  It helps me think of edge cases that I didn't think of when I was originally designing my program.

I know I am finished writing implementation code when all of my test cases pass.

Getting into the habit of writing tests before code also has the added effect of being able to prove that your code has not added any new bugs (assuming you've written good test cases).


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
Math Refresher for Scientists and Engineers

John R. Fanchi


答:
If you work in a company setting you could look for a mentor there.

As for an open source project, I doubt you will find a mentor for a project you create, but you might find one at a project they created.

Don't forget that they mentor needs to get something from this arrangement also. They are spending their valuable time helping you. Be prepared to do some work for them in exchange.

Title: How to find a programming mentor?

Body:
I decided to learn programming. I've been reading SO for few days, and I think I will start with C++, as I read some articles. I am aware of loops, arrays, program logic and objects a little and I need someone to look me over and help me with small questions I get when doing my first projects.

So here is the question - where do I find such guy? I don't got any friends who program and all.

EDIT: 2 years later, I am still looking for mentor. I did not actively code just started 3 months again. I work on Objective-C and iOS programming and game programming with Cocos2d. If you want to become my mentor, drop me a or comment.


答:
Arguably, the TIOBE index isn’t a good criterion. Also, arguably some languages have already caught on. Scala and Clojure in particular seem to stick out (at least on Stack Overlflow).

I actually expect Scala to gain quite a bit on Java in the next few years. Remember, it takes many years for languages to really gain traction and most of these alternative languages haven’t been around for that long.

Java also has gained a few image problems in the past few months (and admittedly this may be short-lived) due to Oracle’s changes in Java politics. This is a big chance for alternative languages to distinguish themselves as worthy alternatives.

Title: Is there any evidence that one of the current alternate JVM languages might catch on?

Body:
There's been a lot of enthusiasm about JRuby, Jython, Groovy, and now Scala and Clojure as the language to be the successor to Java on the JVM.

But currently only Groovy and Scala are in the TIOBE top 100, and none are in the top 50.  Is there any reason to think that any of this bunch will ever gain significant adoption?

My question is not primarily about TIOBE, but about any evidence that you might see that could indicate that one of these languages could get significant backing that goes beyond the enthusiasts.


答: Just avoid "vanity code". There are plenty of developers out there that do things purely out of vanity (or due to an OCD) and nothing else. My panties really get twisted with those people.</p>

Title: Do you actually write 'clean code'?

Body:
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?


答: I've been using Groovy for more than a year now, and it definitely has it's place. But it's not at all a replacement for Java, but a complement. It's a dynamic scripting language that shares some of its syntax with Java, but only on the surface. You get duck typing and similar features of dynamic languages, but on the other hand, you lose most of the compile time checks Java offers. It's also significantely slower.</p>