问:
Do I have to use GPL for my linux application? If yes, how not to legally?
I've written a linux application that interfaces with a lot of GPL software. My application is written in javascript/HTML/CSS/python and uses MariaDB on a CentOS 7 platform (it also uses jquery and a few simple third party tools); we would like to sell this on our hardware as an appliance. The GPL software we are interfacing with (usually via command line or configuration files) include those mentioned above along with lots of little linux tools (e.g. yum, hdparm, psutils and lots of python modules etc...).

We do not want to publicly release the code we have written, even though it would be pretty easy to reverse engineer a lot of it due to our programming language selections (obviously). We intend to lock down the command line, its to dangerous for our clients to access. We will happily direct the users to where they can download all the GPL software, that we aren't modifying, if we are required to; but we don't want to direct them to our software... why would they pay for software updates if they can get it for free? We couldn't survive like that.

So, assuming you say yes I have to issue the software I write under GPL, how can this be avoided and how much will it cost per distribution... do I have to pay the developer of every little tool I read from or write to? It would seem impossible to manage. MySQL seemed to indicate that I do have to pay them in one area of their site without telling me the price, then that I didn't have to pay them in another area.

I have read GPL many times, and have been researching for months... I still don't understand what I need to do, if anything, to achieve my intent of not having to give my software away (other than get a lawyer we can't afford to tell me). For example, could I sell the appliance with the GPL software on it (using the GPL license), then sell our software separate under whatever license we please? If so, does that mean I only need to make sure they are separate line items on our quotations?

答:
You better get proper legal advice, but if you can avoid linking with GPL software, you can usually avoid distributing your source code. If you are linking, you don't really have any option other than to distribute your code.

This is probably the best guidance you can find:

http://www.gnu.org/licenses/gpl-faq.en.html#MereAggregation

In general, if you can interface with the GPL software only via command line, HTTP requests, etc. you may be safe.


问:
Grid walking explanation
There's a problem on hackerrank.com called Grid Walking.

Here is its description:

You are situated in an N dimensional grid at position (x1,x2,...,xN). The dimensions of the grid are (D1,D2,...DN). In one step, you can walk one step ahead or behind in any one of the N dimensions. (So there are always 2×N possible different moves). In how many ways can you take M steps such that you do not leave the grid at any point? You leave the grid if at any point xi, either xi≤0 or xi>Di.

I'm not looking for the solution, no. I'm looking for the explanation of the statement. I need to confess that I don't understand the problem (maybe due to my poor English). For me it feels like the task is about being situated in a multidimensional array (and the phrase here are always 2×N possible different moves seems to confirm that) and walking inside it without going out of its boundaries. Yet, some points need clarification for me and some just contradict this idea of mine. So here I have few questions:

1) What is N dimensional grid? Is it simply N dimensional array? Am I right?

2) What is position (x1,x2,...,xN)? Is it simply current position in the array like [3][4][5]?

3) What is dimensions of the grid are (D1,D2,...DN)? Is it simply lengths for every dimension of the array?

If all my assumptions are correct then the task seems to be more or less understandable, but it seems like they are totally incorrect because input format description breaks everything I have assumed and brings me into absolute confusion:

The first line contains the number of test cases T. T test cases follow. For each test case, the first line contains N and M, the second line contains x1,x2,…,xN and the 3rd line contains D1,D2,…,DN.

Let's have a look at the sample input:

```<code>10
1 287
44
78
1 236
25
87
1 122
41
63
1 260
7
64
1 127
3
73
1 69
6
68
1 231
14
63
1 236
13
30
1 259
38
70
1 257
11
12
</code>```

Here I have few more questions:

1) As you can see all the test cases have 1 for N. But... why? Does it mean that the array(grid) has just one dimension? Or what? I'm completely lost at this point.

2) the second line contains x1,x2,…,xN. And for the first test case it is 44. For the rest of the test cases it is also just one number. What? How can it represent a position? Does it mean that x1,x2,…,xN is something completely different from what I thought it is? Then what does it mean?

3) the 3rd line contains D1,D2,…,DN. As I know from the statement D1, D2, ..., DN is the dimensions of the grid. And again, just like with the previous question it is just one number. 78 for the first test case. But how 78 can represent the dimensions? for 1 dimensional array? Maybe it just means that indeed the array is 1 dimensional, its only dimension is 78 in length and I'm situated on the 44th position? But M which is 287 breaks this assumption too.

As you can see I'm totally confused and really need your help. Would anyone clarify this for me? Thanks a lot

答:
For the first questions:

1) yes

2) yes

3) yes

For the others, you are right as well.

Apparently, all test cases have dimension 1. It's quite silly, indeed.

So the first of the 10 test cases would be:

```<code>1 287
44
78
</code>```

Translated in english:

Given an array of dimension 1 and length 78. Assume you start at
  position 44. In how many ways can you take 287 steps such that you do
  not leave the array at any point?

ContentLicense: CC BY-SA 3.0

Title: Grid walking explanation

Body:
For the first questions:

1) yes

2) yes

3) yes

For the others, you are right as well.

Apparently, all test cases have dimension 1. It's quite silly, indeed.

So the first of the 10 test cases would be:

1 287
44
78

Translated in english:

Given an array of dimension 1 and length 78. Assume you start at
  position 44. In how many ways can you take 287 steps such that you do
  not leave the array at any point?


问:
A pattern to find out if data in a dialog-window was modified by the user?
I think about if there is a pattern or another intelligent solution for that problem. I am searching for a more generalized and reusable solution.

I load an existing and still persistent row/object from a database and display this data in a editable dialog-window to the user.

When closing the window I want to know if the user modfied the data in that dialog. e.g. I should write that modifications back to the database instance and store it.

I could simply check each attribut from the window with the database. Or I could add event-handlers to each component of the window that will set a isModified-flag or something like that. But this doesn't sounds intelligent to me.

Maybe there is a more generalized reusable solution for that?

答:
Event-handlers: useful when you want to know in "realtime" if something has changed

Simple check: useful when you want to lazily know if something has changed

As it is important for you to know this when the window is closing, I'll go with option 2.


问:
Should I add a layer to keep object always valid and immutable?
I am developing COM. A factory need to be initialized first by providing a ID. I can not pass arguments to IFactory instance via CoCreateInstance. So IFactory may need add a init method to be called then. (as approach 2)

I don't want to require client to call init explicitly (they may forget). So that I add a layer named IEntryPoint. This ensures GetFactory will return a verified IFactory without called init first. Then the IFactory instance will not have the state denoted it is valid or invalid. All its methods can be const. (as approach 1)

Is it over encapsulated if IEntryPoint only has GetFactory method?

Approach 1:
IEntryPoint::GetFactory ensures IFactory instance is valid if S_OK is returned.

```<code>interface IEntryPoint
{
    HRESULT GetFactory(size_t id, IFactory** ppFactory) const;
};

interface IFactory
{
    HRESULT GetInstance(size_t id, IInstance** ppInstance) const;
};

interface IInstance
{
    HRESULT Getter1() const;
    HRESULT Getter2() const;
    HRESULT Getter3() const;
};
</code>```

vs

Approach 2:
IFactory instance requires client to call init first.

```<code>interface IFactory
{
    HRESULT Init(size_t id);
    HRESULT GetInstance(size_t id, IInstance** ppInstance) const;
};

interface IInstance
{
    HRESULT Getter1() const;
    HRESULT Getter2() const;
    HRESULT Getter3() const;
};
</code>```

答:
I don't want to required client to call init explicitly (they may forget)

As you said, approach 2 induces a temporal coupling which is really error-prone (user can forget to call Init and let a factory in an undefined state).

Obsviously, the best way to resolve this problem would be to provide the ID when constructing a implementation of IFactory. But since you're using COM and you can't pass arguments to the constructor, adding this layer (IEntryPoint) is the best way to limit this temporal coupling by encapsulating it and making it explicit in IEntryPoints's implementation(s).


答:
I am not a lawyer so don't take my advice seriously. And I am a free software enthusiast so I am biased.

I believe you should at the very least offer your advanced user the technical and legal possibility to upgrade the GPL software that your appliance is using. Read more about TIVOization and the difference between GPLv2 & GPLv3

So if your appliance is using Python 3.4.3 your user should be given the possibility to replace that Python 3.4.3 (e.g. your /usr/bin/python) with a Python 3.5 that your user have compiled (or downloaded from elsewhere) and even perhaps patched (or an Python 2.7.2 to Python 2.7.3 upgrade, if you prefer).

Notice that an advanced user like me might patch Python to upload the bytecode, or even its execution trace, outside of your appliance

You might perhaps make your own python code (e.g. the bytecode) with a proprietary license, but you should not forbid your user to upgrade the /usr/bin/python etc.

I guess that you could state that upgrading software on your appliance would void the warranty. But this point is tricky, is changing from one country to another (AFAIK, laws are slightly different in France, in Germany, in Italy and in the USA about that matter; and things are different for a consumer appliance and for equipments sold to professionals). BTW, that point is IIUC one of the motivations (in France) of the CECILL license

Notice that AFAIK you can write and sell proprietary software in Python (but I don't know much about that point, it is a guess; you should check). But I believe your advanced user should be given the mean to upgrade the Python interpreter (e.g. the /usr/bin/python ELF executable)

In general, in your appliance, you should make a clear distinction between free software that your are using (IMHO the user should be able to upgrade it) and proprietary software that you are selling.

Notice also that what is technically possible is not the same as what is legally permitted. In France, I could go to jail (article 323-1 du Code Pénal) for 2 years by simply accessing a computer system which is not legally permitted to me (even if that is technically easy). I have absolutely no idea about the relevant jurisprudence.

You might ask free software organizations (maybe FSF, or in France APRIL, AFUL, ...) about that. And probably, opensource is a better place to ask.

Read also the GPL violations vendor FAQ.

Title: Do I have to use GPL for my linux application? If yes, how not to legally?

Body:
I've written a linux application that interfaces with a lot of GPL software. My application is written in javascript/HTML/CSS/python and uses MariaDB on a CentOS 7 platform (it also uses jquery and a few simple third party tools); we would like to sell this on our hardware as an appliance. The GPL software we are interfacing with (usually via command line or configuration files) include those mentioned above along with lots of little linux tools (e.g. yum, hdparm, psutils and lots of python modules etc...).

We do not want to publicly release the code we have written, even though it would be pretty easy to reverse engineer a lot of it due to our programming language selections (obviously). We intend to lock down the command line, its to dangerous for our clients to access. We will happily direct the users to where they can download all the GPL software, that we aren't modifying, if we are required to; but we don't want to direct them to our software... why would they pay for software updates if they can get it for free? We couldn't survive like that.

So, assuming you say yes I have to issue the software I write under GPL, how can this be avoided and how much will it cost per distribution... do I have to pay the developer of every little tool I read from or write to? It would seem impossible to manage. MySQL seemed to indicate that I do have to pay them in one area of their site without telling me the price, then that I didn't have to pay them in another area.

I have read GPL many times, and have been researching for months... I still don't understand what I need to do, if anything, to achieve my intent of not having to give my software away (other than get a lawyer we can't afford to tell me). For example, could I sell the appliance with the GPL software on it (using the GPL license), then sell our software separate under whatever license we please? If so, does that mean I only need to make sure they are separate line items on our quotations?


问:
Does syntax really matter in a programming language?
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.

答:
Yes and no.

There are a couple different aspects to syntax.

readability

expressivity

parsability

Readability has already been mentioned.

Expressivity is an interesting case. I'm going to use function-passing as an example, because it's sort of an inflection point of semantic/syntactic pain.

Let's take C++ for example. I can create a first-order function after this fashion:

```<code>class funcClass
{
  int operator()(int);
}
funcClass fun;

void run_func(funcClass fun)
{
   fun();
}
</code>```

This particular idiom is commonly used in Stepanov's Elements of Programming.

On the other hand, I can mimic it in Common Lisp with something like this:

```<code>(defun myfunc() )

(defun run_func(fun)
  (fun))
</code>```

Or, in Perl -

```<code>   sub myfunc
   {
   }

   sub run_func
   {
      my $func = shift;
      $func->();          #syntax may be a little off.
   }
</code>```

Or, in Python -

```<code>def myfunc():
    pass

def run_func(f):
    f()
</code>```

These all have - essentially - the same semantic content, although the C++ example carries some type metadata. Which language expresses the idea of passing a higher-order function the best? Common Lisp barely makes a syntactical variation. C++ requires a class to be created just to 'carry' the function. Perl is pretty straightforward about making some level of differentiation. So is Python.

Which approach best suits the problem domain? Which approach best can express the thoughts in your head with the least 'impedance mismatch'?

Parsability is - in my mind- a big deal. In particular, I refer to the ability of the IDE to parse and chop the language without making errors. Reformatting is useful. Token-delimited languages tend to parse well - ruby/c/pascal, etc.

Consider though - major systems of all sorts have been created with every serious language to solve real-world issues. Although syntax is a barrier to express some things, it is a work-around-able barrier. Turing equivalence and all that.

Body:
Yes and no.

There are a couple different aspects to syntax.

readability

expressivity

parsability

Readability has already been mentioned.

Expressivity is an interesting case. I'm going to use function-passing as an example, because it's sort of an inflection point of semantic/syntactic pain.

Let's take C++ for example. I can create a first-order function after this fashion:

class funcClass
{
  int operator()(int);
}
funcClass fun;

void run_func(funcClass fun)
{
   fun();
}

This particular idiom is commonly used in Stepanov's Elements of Programming.

On the other hand, I can mimic it in Common Lisp with something like this:

(defun myfunc() )

(defun run_func(fun)
  (fun))

Or, in Perl -

   sub myfunc
   {
   }

   sub run_func
   {
      my $func = shift;
      $func->();          #syntax may be a little off.
   }

Or, in Python -

def myfunc():
    pass

def run_func(f):
    f()

These all have - essentially - the same semantic content, although the C++ example carries some type metadata. Which language expresses the idea of passing a higher-order function the best? Common Lisp barely makes a syntactical variation. C++ requires a class to be created just to 'carry' the function. Perl is pretty straightforward about making some level of differentiation. So is Python.

Which approach best suits the problem domain? Which approach best can express the thoughts in your head with the least 'impedance mismatch'?

Parsability is - in my mind- a big deal. In particular, I refer to the ability of the IDE to parse and chop the language without making errors. Reformatting is useful. Token-delimited languages tend to parse well - ruby/c/pascal, etc.

Consider though - major systems of all sorts have been created with every serious language to solve real-world issues. Although syntax is a barrier to express some things, it is a work-around-able barrier. Turing equivalence and all that.

ContentLicense: CC BY-SA 2.5


答: Your biggest problem is likely to be your dependency on mariadb. See their licensing faq at https://mariadb.com/kb/en/mariadb/licensing-faq/ for full details, but briefly their opinion on the interpretation of the GPL in the case of using their server is that if your software is distributed with their server and is not functional if it is removed, you are bound by the GPL. Suggested solutions include the use of a database abstraction later to allow the end user a choice of database servers.</p>


问:
In general, is it worth using virtual functions to avoid branching?
There seems to be rough equivalents of instructions to equate to the cost of a branch miss virtual functions have a similar tradeoff:

instruction vs. data cache miss

optimization barrier

If you look at something like:

```<code>if (x==1) {
   p->do1();
}
else if (x==2) {
   p->do2();
}
else if (x==3) {
   p->do3();
}
...
</code>```

You could have a member function array, or if many functions depend on the same categorization, or more complex categorization exists, use virtual functions:

```<code>p->do()
</code>```

But, in general, how expensive are virtual functions vs branching
It is hard to test on enough platforms to generalize, so I was wondering if any one had a rough rule of thumb (lovely if it were as simple as 4 ifs is the breakpoint)

In general virtual functions are clearer and I would lean towards them.  But, I have several highly critical sections where I can change code from virtual functions to branches. I would prefer to have thoughts on this before I undertake this. (it's not a trivial change, or easy to test across multiple platforms)

答:
In general, is it worth using virtual functions to avoid branching?

In general, yes. The benefits for maintenance are significant (testing in separation, separation of concerns, improved modularity and extensibility).

But, in general, how expensive are virtual functions vs branching It is hard to test on enough platforms to generalize, so I was wondering if any one had a rough rule of thumb (lovely if it were as simple as 4 ifs is the breakpoint)

Unless you have profiled your code and know the dispatch between branches (the conditions evaluation) takes more time than the computations performed (the code in the branches), optimize the computations performed.

That is, the correct answer to "how expensive are virtual functions vs branching" is measure and find out.

Rule of thumb: unless have the situation above (branch discrimination more expensive than branch computations), optimize this part of the code for maintenance effort (use virtual functions).

You say that you want this section to run as fast as possible; How fast is that? What's your concrete requirement?

In general virtual functions are clearer and I would lean towards them. But, I have several highly critical sections where I can change code from virtual functions to branches. I would prefer to have thoughts on this before I undertake this. (it's not a trivial change, or easy to test across multiple platforms)

Use virtual functions then. This will even allow you to optimize per platform if necessary, and still keep client code clean.


问:
How to reconcile "not mocking what you don't own" with "expectations" in unit tests?
I'm putting together a set of models for use in a Zend Framework 2 application. So, each model has a table class which acts as the interface between the model and database for querying. Using the ZF2 TableGateway means that even a fairly simple query, like getting the number of hits from a page log between two dates, ends up with some complex calls:

public function getDailyHits($start, $end)
{
    $select = $this->tableGateway->getSql()->select();

    $select->columns(array(
            "date" => new Expression("DATE_FORMAT(timestamp, '%Y-%m-%d')"),
            "hits" => new Expression("COUNT(timestamp)"),
        ));

    $select->where->between("timestamp", $start, $end);

    $select->group("date");

    $results = $this->tableGateway->selectWith($select);

    $dailyHits = array();
    foreach ($results as $result) {
        $dailyHits[$result->date] = $result->hits;
    }

    return $dailyHits;
}
```

<p>When it came to developing the unit test, I wrote up a bunch of expectations:</p>

<pre class="lang-php prettyprint-override"><code>public function testGetDailySearches()
{
    // Setup
    $result = new \stdClass();
    $result->date = "2015-01-01";
    $result->searches = 42;

    $resultSet = array($result);

    $sql = $this->getMockBuilder("Zend\Db\Sql\Sql")
        ->disableOriginalConstructor()
        ->getMock();

    $select = $this->getMockBuilder("Zend\Db\Sql\Select")
        ->disableOriginalConstructor()
        ->getMock();

    $where = $this->getMockBuilder("Zend\Db\Sql\Where")
        ->disableOriginalConstructor()
        ->getMock();

    $tableGateway = $this->getMockBuilder("Zend\Db\TableGateway\TableGateway")
        ->disableOriginalConstructor()
        ->getMock();

    $searchLogTable = $this->getMockBuilder("Usage\Model\Table\SearchLog")
        ->setConstructorArgs(array($tableGateway))
        ->setMethods(null)
        ->getMock();

    // Expectations
    $tableGateway->expects($this->once())
        ->method("getSql")
        ->will($this->returnValue($sql));

    $tableGateway->expects($this->once())
        ->method("selectWith")
        ->with($this->equalTo($select))
        ->will($this->returnValue($resultSet));

    $sql->expects($this->once())
        ->method("select")
        ->will($this->returnValue($select));

    $select->expects($this->once())
        ->method("columns")
        ->will($this->returnValue($select)); // TODO: need to assert parameters

    $select->expects($this->once())
        ->method("__get")
        ->with($this->equalTo("where"))
        ->will($this->returnValue($where));

    $where->expects($this->once())
        ->method("between")
        ->with(
            $this->equalTo("time"),
            $this->equalTo("2015-10-01 00:00:00"),
            $this->equalTo("2015-10-07 23:59:59")
        )
        ->will($this->returnValue($select));

    $select->expects($this->once())
        ->method("group")
        ->with($this->equalTo("date"));

    // Assertions
    $this->assertEquals(
        array("2015-01-01" => 42),
        $searchLogTable->getDailySearches("2015-10-01 00:00:00", "2015-10-07 23:59:59")
    );
}
</code>```

I had a go at using Prophecy to reduce the verbosity in these tests, but got tripped up on them magic __get method needed to read the $where property from the Select object.

After reading through a couple of threads on the Prophecy site, I uncovered a link to That's Not Yours. It makes a lot of sense. It also would reduce a lot of boilerplate in some tests if I just subclass TableGateway (or even maybe just mock it) so that all the Zend\Db behaviour is retained.

But, then what happens to my expectations? Is this a case of overengineered testing? Should I have these expectations, or should I rely on testing a mostly black box of a method?

If I did remove those expectations, and relied on a mocked result from the subclassed/mocked selectWith, I could write a passing test which didn't specify any of the select criteria, and would fail to function as required in the real world.

答:
The basic idea behind the advice you quote is that where you have a piece of code that:

interacts with some external service (eg your database), and

also contains application logic (eg processes data retrieved from the database)

it is best to split the code in two, because those two different responsibilities need to be tested in different ways:

you create a module that presents the simplest possible interface to your own code, and which encapsulates all of the complexity of interacting with the external service - this module is best tested with integration tests

you then develop a module with your application logic that uses the simplified interface module. This simplified module should be easier to replace with a mock, and you're more likely to fully understand its behaviour so you are less likely to write a mock that behaves incorrectly. You can therefore test the complex logic more easily using simpler unit tests.

Note that your interface module shouldn't subclass an external class - to get the full benefit of the principle, you should only include as much complexity in its interface as you absolutely require. Prefer aggregation over inheritance is the maxim to apply here.


问:
must all urls for a resource be same
I have a Resource named Company, that can have Post Resource,

I have a path for create of post as:
POST /api/company/{companyName}/post.

My question is whether, must i use a path as
PUT /api/company/{companyName}/post/{postId}
or PUT /api/company/post/{postId} for Update of post resource?

答:
For nested resources like this you will find both options.

```<code>/api/company/{companyName}/post/{postId}
</code>```

would be the more detailed variant. While

```<code>/api/company/post/{postId}
</code>```

is more concise (obviously it requires postId to be unique and the record to have a reference to the companyId).

For Ruby on Rails this type of routes is called shallow nesting and very often used and recommended. Though (at least for Rails) you would in such a case obviously have a third option and omit the company part completely:

```<code>/api/post/{postId}
</code>```

unless you need this for anything else inside your code or have different types of posts that are handled differently.

There are not really any clear rules for that scenario (to my best knowledge). A URI only must be able to find a resource. You can even have multiple routes point to the same resource (just make sure you don't duplicate the code to handle them).

I would want to keep things simple, so at least decide for one variant and implement all necessary actions with that route. But it mostly depends on your use case and what makes most sense for the clients of your API.

So if you implement PUT and POST with different routes I would implement both methods on both variants (if there is a chance they will be used at all). So the client can decide if he wants to use /api/company/post/{post_id} or prefers /api/post/{post_id} but does not have to switch between both of them for no obvious reason.

Title: must all urls for a resource be same

Body:
For nested resources like this you will find both options.

/api/company/{companyName}/post/{postId}

would be the more detailed variant. While

/api/company/post/{postId}

is more concise (obviously it requires postId to be unique and the record to have a reference to the companyId).

For Ruby on Rails this type of routes is called shallow nesting and very often used and recommended. Though (at least for Rails) you would in such a case obviously have a third option and omit the company part completely:

/api/post/{postId}

unless you need this for anything else inside your code or have different types of posts that are handled differently.

There are not really any clear rules for that scenario (to my best knowledge). A URI only must be able to find a resource. You can even have multiple routes point to the same resource (just make sure you don't duplicate the code to handle them).

I would want to keep things simple, so at least decide for one variant and implement all necessary actions with that route. But it mostly depends on your use case and what makes most sense for the clients of your API.

So if you implement PUT and POST with different routes I would implement both methods on both variants (if there is a chance they will be used at all). So the client can decide if he wants to use /api/company/post/{post_id} or prefers /api/post/{post_id} but does not have to switch between both of them for no obvious reason.


答:
I could simply check each attribut from the window with the database

Its better to check the data has changed before sending it to the DB. So I would read the data to be displayed into local storage (I found the best way was a map array of variables keyed by control name), copy that into the GUI control and then check the differences when the GUI is closed - if the data is different, then send it to the DB.

Title: A pattern to find out if data in a dialog-window was modified by the user?

Body:
I think about if there is a pattern or another intelligent solution for that problem. I am searching for a more generalized and reusable solution.

I load an existing and still persistent row/object from a database and display this data in a editable dialog-window to the user.

When closing the window I want to know if the user modfied the data in that dialog. e.g. I should write that modifications back to the database instance and store it.

I could simply check each attribut from the window with the database. Or I could add event-handlers to each component of the window that will set a isModified-flag or something like that. But this doesn't sounds intelligent to me.

Maybe there is a more generalized reusable solution for that?


问:
Can version control systems use the filesystem log to capture changes?
I was trying to find a "perfect" syncing program between a network share and a local folder, when I realised that it's probably impossible to do it right unless all the filesystem operations were captured by a log of some sort, that could then be replayed on the remote server. Of course the same thing is required at the other end for retrieving changes from the remote server, but one could also use the existing system for that purpose, and if worst comes to worst, manual merging.

The advantage of this approach seems to be that handling deletes, renames, moves and copies, etc., become trivial, because the filesystem records these operations. Each commit would then consist of merely choosing the next meaningful changed version. The version control log would be a low-resolution version of the filesystem log, but will be more portable and persistent because it can be transported.

Is this viable, or have I understood the concepts and limitations wrong?

答:
You've misunderstood because the filesystem transaction log is a very temporary beast, it does not hang around long enough to be used for history (at least in no filesystem I know of).

But otherwise, yes - its a valid principle. The VCS log would be the only log you have however. It cannot be transported though as it is not a transaction log, it a 'living' history of operations. You could transport the view of this history however.

Sync is already implemented like this - SVNSync does exactly the replay operations you describe.


问:
UML class diagram symbol for a top-level function
In UML class diagram notation, how do I denote a top-level function that doesn't have any encapsulating class or other structure?

e.g. I have a function used for retrieving data from a URL. Since it is a function (in the math sense) of only its parameters and a shared global state, the function is not put in a class but left as a top-level method.

Now though, I need to create a UML diagram for a program using it, and I can't find anything about how to denote a top-level function. How do I do this?

答:
The UML language does not support the notion of stand-alone functions. Within UML, all functions must be part of a class.

As a work-around, you could model your stand-alone functions as static members of a class they are closely related to. If there is no such class, then you could model those functions as being part of a dummy class, like the global class mentioned by @xmojmr in the comments.


答:
File system operations are actually often at a coarser granularity than the changes that VCS tracks. A file may be over-written in a single operation, when only a line has really been changed.

Other times, the file system operations are too fine-grained and miss the big picture. Someone may "copy" a file and then rewrite everything except the copyright notice. Or they may delete a file, copy it from somewhere else under a new name but with the same contents.

VCS does the right thing in computing diffs directly on what's in the files rather than analyzing file system operations. The latter would be far more fragile and headache-inducing.

Title: Can version control systems use the filesystem log to capture changes?

Body:
I was trying to find a "perfect" syncing program between a network share and a local folder, when I realised that it's probably impossible to do it right unless all the filesystem operations were captured by a log of some sort, that could then be replayed on the remote server. Of course the same thing is required at the other end for retrieving changes from the remote server, but one could also use the existing system for that purpose, and if worst comes to worst, manual merging.

The advantage of this approach seems to be that handling deletes, renames, moves and copies, etc., become trivial, because the filesystem records these operations. Each commit would then consist of merely choosing the next meaningful changed version. The version control log would be a low-resolution version of the filesystem log, but will be more portable and persistent because it can be transported.

Is this viable, or have I understood the concepts and limitations wrong?


问:
Inheritance when following the Repository Pattern in PHP
I am trying to build a PHP application using the Repository Pattern but I'm not sure how I should implement the save method.

I have an abstract class called ItemRepository which have the following method:

```<code>abstract class ItemRepository
{
    public function save(Item $item);
}
</code>```

Where Item also is an abstract class.

Now I want to implement the class MovieRepository which extends ItemRepository. Here I want to save instances of the Movie class which extends Item.

Though doing it like this in PHP

```<code>// MovieRepository.php
class MovieRepository extends ItemRepository
{
    public function save(Movie $movie)
    {
        ...
    }
}
</code>```

gives the following error

Declaration of MovieRepository::save() should be compatible with ItemRepository::save(Item $item)

What is the right way to do this?

答:
I'm going to guess, that what you're trying to do, is have a common implementation of save() but exposed with the correct type-check for each repository type? (You didn't declare save() as abstract in your ItemRepository, so I'm guessing you had a method body in there?)

Since the argument-type for save() in different repository types are going to differ, we're not talking about the same save() method - in other words, naming the method save() in each repository type is going to be a convention, but they are different methods, since e.g. save(Movie $movie) is incompatible with save(Item $item), because Movie is an Item, but an Item is not necessarily a Movie.

Based on that, I would suggest extracting an internal save-method into an abstract base-class.

abstract class AbstractItemRepository {
    protected function saveItem(Item $item) {
        // ...
    }
}

class ItemRepository extends AbstractItemRepository {
    public function save(Item $item) {
        $this->saveItem($item);
    }
}

class MovieRepository extends AbstractItemRepository {
    public function save(Movie $movie) {
        $this->saveItem($movie);
    }
}
```

In other words, put shared functionality in an abstract base class - but leave the public interface definition up to the individual implementation.

That said, please see answer by @GregBurghardt who points out:

Unless the ItemRepository and MovieRepository classes are actually related, then you don't need a parent class

In other words, if the save functionality isn't a common implementation, there's no point in trying to abstract this, beyond maybe trying to enforce a method naming convention; but that's not really what abstraction is for.

Body:
I'm going to guess, that what you're trying to do, is have a common implementation of save() but exposed with the correct type-check for each repository type? (You didn't declare save() as abstract in your ItemRepository, so I'm guessing you had a method body in there?)

Since the argument-type for save() in different repository types are going to differ, we're not talking about the same save() method - in other words, naming the method save() in each repository type is going to be a convention, but they are different methods, since e.g. save(Movie $movie) is incompatible with save(Item $item), because Movie is an Item, but an Item is not necessarily a Movie.

Based on that, I would suggest extracting an internal save-method into an abstract base-class.

abstract class AbstractItemRepository {
    protected function saveItem(Item $item) {
        // ...
    }
}

class ItemRepository extends AbstractItemRepository {
    public function save(Item $item) {
        $this->saveItem($item);
    }
}

class MovieRepository extends AbstractItemRepository {
    public function save(Movie $movie) {
        $this->saveItem($movie);
    }
}

In other words, put shared functionality in an abstract base class - but leave the public interface definition up to the individual implementation.

That said, please see answer by @GregBurghardt who points out:

Unless the ItemRepository and MovieRepository classes are actually related, then you don't need a parent class

In other words, if the save functionality isn't a common implementation, there's no point in trying to abstract this, beyond maybe trying to enforce a method naming convention; but that's not really what abstraction is for.


问:
Saga's and Query model transaction ordering
I have the following Ubiquitous language defined by our domain expert: A User can find UserGroups and add himself to it. A user can query a list of UserGroups where he is member of and remove himself from it. UserGroups are created by Users, where the creator is the first member. When there is no more User in the UserGroup, the UserGroup should be deleted from the views.

As UserGroups can become pretty big, by following "Effective Aggregate Design", I came to the following {AR}'s:

{User}<--(UserId)--{UserGroupMember}--(UserGroupId)-->{UserGroup}

All fine, except how to make the last rule (When there is no more User in the UserGroup, the UserGroup should be deleted from the views.) work with this model?

I've considered a saga that listens to UserGroupMemberLeft event, queuing the nr of members and if 0 delete the group. But as it queries the read-model, I have an ordering problem as the read-model is eventually updated as well. How to solve this? Should I consider a ReadModelUpdated event as well?

答:
The thing lacking in your domain language is the concept of WHO should delete the group. Users can create groups and add themselves to it, which puts the responsibility for those actions clearly on the users. But you go on to say that 'groups should be deleted'. From a business perspective, this makes no sense.

If your requirement is rephrased to "When there is no more User in the UserGroup, the User should delete the group " it becomes obvious who's responsibility it is to remove the group.


问:
Best practices regarding type mapping and extension methods
I want to ask some questions about best practices regarding mapping types and using extension methods in C#. I know this topic has been discussed multiple times over past few years, but I've read a lot of posts and still have doubts.

The problem I encountered was extending class that I own with "convert" functionality. Let's say that I have class "Person" that represents an object which will be used by some logic. I also have a class "Customer" that represents a response from external API (actually there will be more than one API, so I need to map each API's response to common type: Person). I have access to both classes' source code and theoretically can implement my own methods there. I need to convert Customer to Person so I can save it to database. The project doesn't use any automatic mappers.

I have 4 possible solutions in mind:

.ToPerson() method in Consumer class. It's simple, but it seems like breaking the Single Responsibility pattern to me, especially that the Consumer class is mapped to other classes (some required by another external API) as well, so it would need to contain multiple mapping methods.

Mapping constructor in Person class taking Consumer as an argument. Also easy and also seems like breaking Single Responsibility pattern. I'd need to have multiple mapping constructors (since there will be class from another API, providing the same data as Consumer but in slightly different format)

Converters class with extension methods. This way I can write .ToPerson() method for Consumer class and when another API is introduced with it's own NewConsumer class, I can just write another extension method and keep it all in the same file. I've heard an opinion that extension methods are evil in general and should be used only if absolutely necessary so that's what is holding me back. Otherwise I like this solution

Converter/Mapper class. I create separate class that will handle conversions and implement methods that will take source class instance as an argument and return destination class instance.

To sum up, my problem can be reduced to number of questions (all in context to what I described above):

Is putting conversion method inside (POCO?) object (like .ToPerson() method in Consumer class) considered breaking single responsibility pattern?

Is using converting constructors in (DTO-like) class considered breaking single responsibility pattern? Especially if such class can be converted from multiple source types, so multiple converting constructors would be required?

Is using extension methods while having access to original class source code considered bad practice? Can such behavior be used as viable pattern for separating logic or is it an anti-pattern?

答:
How about using AutoMapper or custom mapper could be used Like

```<code>MyMapper
   .CreateMap<Person>()
   .To<PersonViewModel>()
   .Map(p => p.Name, vm => vm.FirstName)
   .To<SomeDTO>()
   .Map(...);
</code>```

from domain

```<code> db.Persons
   .ToListAsync()
   .Map<PersonViewModel>();
</code>```

Under the hood you could abstract AutoMapper or roll your own mapper

Body:
How about using AutoMapper or custom mapper could be used Like

MyMapper
   .CreateMap<Person>()
   .To<PersonViewModel>()
   .Map(p => p.Name, vm => vm.FirstName)
   .To<SomeDTO>()
   .Map(...);

from domain

 db.Persons
   .ToListAsync()
   .Map<PersonViewModel>();

Under the hood you could abstract AutoMapper or roll your own mapper


答:
Is putting conversion method inside (POCO?) object (like .ToPerson() method in Consumer class) considered breaking single responsibility pattern?

Yes, because conversion is another responsibility.

Is using converting constructors in (DTO-like) class considered breaking single responsibility pattern? Especially if such class can be converted from multiple source types, so multiple converting constructors would be required?

Yes, conversion is another responsibility. It makes no difference if you do it via constructors or via conversion methods (e.g. ToPerson).

Is using extension methods while having access to original class source code considered bad practice?

Not necessarily. You can create extension methods even if you have the source code of the class that you want to extend. I think that whether you create an extension method or not should be determined by the nature of such method. For example, does it contain a lot of logic? Does it depend on anything other that the members of the object itself? I would say that you shouldn't have an extension method that requires dependencies to work or that contains complex logic. Only the simplest of logic should be contained in an extension method.

Can such behavior be used as viable pattern for separating logic or is it an anti-pattern?

If the logic is complex, then I think that you shouldn't use an extension method. As I noted earlier, you should use extension methods only for the simplest things. I wouldn't consider conversion simple.

I suggest that you create conversion services. You can have a single generic interface for it like this:

```<code>public interface IConverter<TSource,TDestination>
{
    TDestination Convert(TSource source_object);
}
</code>```

And you can have converters like this:

```<code>public class PersonToCustomerConverter : IConverter<Person,Customer>
{
    public Customer Convert(Person source_object)
    {
        //Do the conversion here. Note that you can have dependencies injected to this class
    }
}
</code>```

And you can use Dependency Injection to inject a converter (e.g. IConverter<Person,Customer>) to any class that requires the ability to convert between Person and Customer.

Title: Best practices regarding type mapping and extension methods

Body:
I want to ask some questions about best practices regarding mapping types and using extension methods in C#. I know this topic has been discussed multiple times over past few years, but I've read a lot of posts and still have doubts.

The problem I encountered was extending class that I own with "convert" functionality. Let's say that I have class "Person" that represents an object which will be used by some logic. I also have a class "Customer" that represents a response from external API (actually there will be more than one API, so I need to map each API's response to common type: Person). I have access to both classes' source code and theoretically can implement my own methods there. I need to convert Customer to Person so I can save it to database. The project doesn't use any automatic mappers.

I have 4 possible solutions in mind:

.ToPerson() method in Consumer class. It's simple, but it seems like breaking the Single Responsibility pattern to me, especially that the Consumer class is mapped to other classes (some required by another external API) as well, so it would need to contain multiple mapping methods.

Mapping constructor in Person class taking Consumer as an argument. Also easy and also seems like breaking Single Responsibility pattern. I'd need to have multiple mapping constructors (since there will be class from another API, providing the same data as Consumer but in slightly different format)

Converters class with extension methods. This way I can write .ToPerson() method for Consumer class and when another API is introduced with it's own NewConsumer class, I can just write another extension method and keep it all in the same file. I've heard an opinion that extension methods are evil in general and should be used only if absolutely necessary so that's what is holding me back. Otherwise I like this solution

Converter/Mapper class. I create separate class that will handle conversions and implement methods that will take source class instance as an argument and return destination class instance.

To sum up, my problem can be reduced to number of questions (all in context to what I described above):

Is putting conversion method inside (POCO?) object (like .ToPerson() method in Consumer class) considered breaking single responsibility pattern?

Is using converting constructors in (DTO-like) class considered breaking single responsibility pattern? Especially if such class can be converted from multiple source types, so multiple converting constructors would be required?

Is using extension methods while having access to original class source code considered bad practice? Can such behavior be used as viable pattern for separating logic or is it an anti-pattern?

Body:
Is putting conversion method inside (POCO?) object (like .ToPerson() method in Consumer class) considered breaking single responsibility pattern?

Yes, because conversion is another responsibility.

Is using converting constructors in (DTO-like) class considered breaking single responsibility pattern? Especially if such class can be converted from multiple source types, so multiple converting constructors would be required?

Yes, conversion is another responsibility. It makes no difference if you do it via constructors or via conversion methods (e.g. ToPerson).

Is using extension methods while having access to original class source code considered bad practice?

Not necessarily. You can create extension methods even if you have the source code of the class that you want to extend. I think that whether you create an extension method or not should be determined by the nature of such method. For example, does it contain a lot of logic? Does it depend on anything other that the members of the object itself? I would say that you shouldn't have an extension method that requires dependencies to work or that contains complex logic. Only the simplest of logic should be contained in an extension method.

Can such behavior be used as viable pattern for separating logic or is it an anti-pattern?

If the logic is complex, then I think that you shouldn't use an extension method. As I noted earlier, you should use extension methods only for the simplest things. I wouldn't consider conversion simple.

I suggest that you create conversion services. You can have a single generic interface for it like this:

public interface IConverter<TSource,TDestination>
{
    TDestination Convert(TSource source_object);
}

And you can have converters like this:

public class PersonToCustomerConverter : IConverter<Person,Customer>
{
    public Customer Convert(Person source_object)
    {
        //Do the conversion here. Note that you can have dependencies injected to this class
    }
}

And you can use Dependency Injection to inject a converter (e.g. IConverter<Person,Customer>) to any class that requires the ability to convert between Person and Customer.


答:
Is putting conversion method inside (POCO?) object (like .ToPerson() method in Consumer class) considered breaking single responsibility pattern?

Yes.  A Consumer class is responsible for holding the data related to a consumer (and possibly performing some actions) and should not be responsible for converting itself into another, unrelated type.

Is using converting constructors in (DTO-like) class considered breaking single responsibility pattern? Especially if such class can be converted from multiple source types, so multiple converting constructors would be required?

Probably.  I typically have methods outside both the domain and DTO objects to do the conversion.  I often use a repository that takes in domain objects and (de)serializes them, either to a database, memory, file, whatever.  If I put that logic in my domain classes, now I've tied them to one particular form of serialization, which is bad for testing (and other things).  If I put the logic in my DTO classes, then I've tied them to my domain, again limiting testing.

Is using extension methods while having access to original class source code considered bad practice?

Not in general, although they can be overused.  With extension methods, you create optional extensions that make code easier to read.  They do have drawbacks - it;s easier to create ambiguities that the compiler has to resolve (sometimes silently) and can make code more difficult to debug since it's not entirely obvious where the extension method is coming from.

In your case, a converter or mapper class seems like the simplest, most straightforward approach, although I don't think you're doing anything wrong by using extension methods.


答:
Syntax definitely matters, although you tend to notice it more when it's unintuitive and encourages bugs.  For example, the infamous "world's last bug" joke:</p>

```<code>if (AlertCode = RED)
   {LaunchNukes();}
</code>```

Title: Does syntax really matter in a programming language?

Body:
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.

Body:
Syntax definitely matters, although you tend to notice it more when it's unintuitive and encourages bugs.  For example, the infamous "world's last bug" joke:

if (AlertCode = RED)
   {LaunchNukes();}


问:
Are (database) integration tests bad?
Some people maintain that integration tests are all kinds of bad and wrong - everything must be unit-tested, which means you have to mock dependencies; an option which, for various reasons, I'm not always fond of.

I find that, in some cases, a unit-test simply doesn't prove anything.

Let's take the following (trivial, naive) repository implementation (in PHP) as an example:

class ProductRepository
{
    private $db;

    public function __construct(ConnectionInterface $db) {
        $this->db = $db;
    }

    public function findByKeyword($keyword) {
        // this might have a query builder, keyword processing, etc. - this is
        // a totally naive example just to illustrate the DB dependency, mkay?

        return $this->db->fetch("SELECT * FROM products p"
            . " WHERE p.name LIKE :keyword", ['keyword' => $keyword]);
    }
}
```

Let's say I want to prove in a test that this repository can actually find products matching various given keywords.

Short of integration testing with a real connection object, how can I know that this is actually generating real queries - and that those queries actually do what I think they do?

If I have to mock the connection object in a unit-test, I can only prove things like "it generates the expected query" - but that doesn't mean it's actually going to work... that is, maybe it's generating the query I expected, but maybe that query doesn't do what I think it does.

In other words, I feel like a test that makes assertions about the generated query, is essentially without value, because it's testing how the findByKeyword() method was implemented, but that doesn't prove that it actually works.

This problem isn't limited to repositories or database integration - it seems to apply in a lot of cases, where making assertions about the use of a mock (test-double) only proves how things are implemented, not whether they're going to actually work.

How do you deal with situations like these?

Are integration tests really "bad" in a case like this?

I get the point that it's better to test one thing, and I also understand why integration testing leads to myriad code-paths, all of which cannot be tested - but in the case of a service (such as a repository) whose only purpose is to interact with another component, how can you really test anything without integration testing?

答:
The author of the blog article you refer to is mainly concerned with the potential complexity that can arise from integrated tests (although it is written in a very opinionated and categorical way).
However, integrated tests are not necessarily bad, and some are actually more useful than pure unit tests. It really depends on the context of your application and what you're trying to test.

Many applications today would simply not work at all if their database server went down. At least, think of it in the context of the feature you're trying to test.

On the one hand, if what you're trying to test doesn't depend, or can be made not to depend at all, on the database, then write your test in such a way that it doesn't even try to use the database (just provide mock data as required).
 For example, if you're trying to test some authentication logic when serving a web page (for example), it's probably a good thing to detach that from the DB altogether (assuming you don't rely on the DB for authentication, or that you can mock it reasonably easily).

On the other hand, if it's a feature that directly relies on your database and that wouldn't work in a real environment at all should the database be unavailable, then mocking what the DB does in your DB client code (i.e. the layer using that DB) doesn't necessarily make sense.

For example, if you know that your application is going to rely on a database (and possibly on a specific database system), mocking the database behaviour for the sake of it often will be a waste of time. Database engines (especially RDBMS) are complex systems. A few lines of SQL can actually perform a lot of work, which would be difficult to simulate (in fact, if your SQL query is a few lines long, chances are you'll need many more lines of Java/PHP/C#/Python code to produce the same result internally): duplicating the logic you've already implemented in the DB doesn't make sense, and checking that test code would then become a problem in itself.

I wouldn't necessarily treat this as a problem of unit test v.s. integrated test, but rather look at the scope of what is being tested.
The overall problems of unit and integration testing remain: you need a reasonably realistic set of test data and test cases, but something that is also sufficiently small for the tests to be executed quickly.

The time to reset the database and repopulate with test data is an aspect to consider; you would generally evaluate this against the time it takes to write that mock code (which you would have to maintain too, eventually).

Another point to consider is the degree of dependency your application has with the database.

If your application simply follows a CRUD model, where you have a layer of abstraction that lets you swap between any RDBMS by the simple means of a configuration setting, chances are you'll be able to work with a mock system quite easily (possibly blurring the line between unit and integrated testing using an in-memory RDBMS).

If your application uses more complex logic, something that would be specific to one of SQL Server, MySQL, PostgreSQL (for example), then it would generally make more sense to have a test that use that specific system.

Title: Are (database) integration tests bad?


问:
IoC container with lifetime attribute
Which ioc frameworks for .net can use concrete type attribute to choose it's lifetime? Here is a simple example</p>

```<code>public interface IService
{}

[Singleton]
public class ServiceImplA : IService
{}

[Transient]
public class ServiceImplB : IService
{}

class Program
{
    static void Main(string[] args)
    {
        //now some pseudocode
        //here choosing ServiceImplA is based on some config file
        container.Register<IService, ServiceImplA>();

        //here i want GetInstance to return the same instance in each call.
        //instanceA should be equal to instanceA2
        var instanceA = container.GetInstance<IService>();
        var instanceA2 = container.GetInstance<IService>();

        //but if do the same for ServiceImplB,
        //i would like to get a new instance after each GetInstance call
    }
}
</code>```

答:
I'd like to post here a piece of documentation from Simple Injector, because it's example perfectly answers my question. Here is a link.

```<code>using System;
using System.Reflection;
using SimpleInjector.Advanced;

// Attribute for use by the application
public enum CreationPolicy { Transient, Scoped, Singleton }

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface,
    Inherited = false, AllowMultiple = false)]
public sealed class CreationPolicyAttribute : Attribute {
    public CreationPolicyAttribute(CreationPolicy policy) {
        this.Policy = policy;
    }

    public CreationPolicy Policy { get; private set; }
}

// Custom lifestyle selection behavior
public class AttributeBasedLifestyleSelectionBehavior : ILifestyleSelectionBehavior {
    private const CreationPolicy DefaultPolicy = CreationPolicy.Transient;

    public Lifestyle SelectLifestyle(Type serviceType, Type implementationType) {
        var attribute = implementationType.GetCustomAttribute<CreationPolicyAttribute>()
            ?? serviceType.GetCustomAttribute<CreationPolicyAttribute>();

        switch (attribute != null ? attribute.Policy : DefaultPolicy) {
            case CreationPolicy.Singleton: return Lifestyle.Singleton;
            case CreationPolicy.Scoped: return Lifestyle.Scoped;
            default: return Lifestyle.Transient;
        }
    }
}

// Usage
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

container.Options.LifestyleSelectionBehavior =
    new AttributeBasedLifestyleSelectionBehavior();

container.Register<IUserContext, AspNetUserContext>();

// Usage in application
[CreationPolicy(CreationPolicy.Scoped)]
public class AspNetUserContext : IUserContext {
    // etc
}
</code>```

Anyway i accept Yacoub's answer, because it shows more general approach and gives some comments about design.

Title: IoC container with lifetime attribute

Body:
I'd like to post here a piece of documentation from Simple Injector, because it's example perfectly answers my question. Here is a link.

using System;
using System.Reflection;
using SimpleInjector.Advanced;

// Attribute for use by the application
public enum CreationPolicy { Transient, Scoped, Singleton }

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface,
    Inherited = false, AllowMultiple = false)]
public sealed class CreationPolicyAttribute : Attribute {
    public CreationPolicyAttribute(CreationPolicy policy) {
        this.Policy = policy;
    }

    public CreationPolicy Policy { get; private set; }
}

// Custom lifestyle selection behavior
public class AttributeBasedLifestyleSelectionBehavior : ILifestyleSelectionBehavior {
    private const CreationPolicy DefaultPolicy = CreationPolicy.Transient;

    public Lifestyle SelectLifestyle(Type serviceType, Type implementationType) {
        var attribute = implementationType.GetCustomAttribute<CreationPolicyAttribute>()
            ?? serviceType.GetCustomAttribute<CreationPolicyAttribute>();

        switch (attribute != null ? attribute.Policy : DefaultPolicy) {
            case CreationPolicy.Singleton: return Lifestyle.Singleton;
            case CreationPolicy.Scoped: return Lifestyle.Scoped;
            default: return Lifestyle.Transient;
        }
    }
}

// Usage
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

container.Options.LifestyleSelectionBehavior =
    new AttributeBasedLifestyleSelectionBehavior();

container.Register<IUserContext, AspNetUserContext>();

// Usage in application
[CreationPolicy(CreationPolicy.Scoped)]
public class AspNetUserContext : IUserContext {
    // etc
}

Anyway i accept Yacoub's answer, because it shows more general approach and gives some comments about design.


问:
"Vendor" name changes when the vendor name changes
PHP (PSR-2, anyway) recommends using the vendor name as the root namespace for projects. At face value, this seems to mean we should use the current name of our company. But I work for an enterprise that has been involved in multiple M&As over the years; the name keeps changing, and the old name often still belongs to someone else. I suppose we could just ignore the recommendation and invent some root namespace that is unlikely to conflict with any future strategic forks in the road, but there is value to the recognition that customers have with the name. The problem is, there's also value to the old name from a marketing perspective, too.

On the legal side, sooner or later we will certainly be obligated not to use the old name. But on the technical side, changing the name introduces some risk, too.

I have to change the root namespace of some of our products, eventually. The question is, should I really keep using our (new, at the time) company name as the "vendor" namespace, or is there a better option that can survive future company name changes (ideally, one that doesn't stray too far from the intent of PSR-2)?

答:
The idea is that the namespace is unique, which is why they suggest using your company name (which may have been OK for Sun when they assumed they were too big to ever fail) but it ignores the practicality of M&As or even 2 companies with the same name.

The alternative is to use a GUID but that's impractical for people so you just do what everyone does and puts up with an imperfect solution. Add a product name to the namespace so it adds an extra layer of uniqueness and you should be OK.

As for renaming for legal reasons - it can be considered that the namespace name is part of the product as it was developed and so its OK to continue using it even if the product no longer belongs to the original company. If there is a definite legal reason it has to be changed, then the lawyers will tell you to change it and you take the hit of updating it then. The alternative is to rebrand the product in a major version update.

Its not that big a deal all in all, look in your registry (if you have Windows) and you'll see plenty of entries that reflect the original name of a product (Macromedia Flash for example - bought out in 2005, still used today)


问:
Why is Math.Sqrt() a static function?
In a discussion about static and instance methods, I always think, that Sqrt() should be a instance method of number types instead of a static method. Why is that? It obviously works on a value.

```<code> // looks wrong to me
 var y = Math.Sqrt(x);
 // looks better to me
 var y = x.Sqrt();
</code>```

Value types obviously can have instance methods, as in many languages, there is an instance method ToString().

To answer some questions from the comments: Why should 1.Sqrt() not be legal? 1.ToString() is.

Some languages do not allow to have methods on value types, but some languages can. I am talking about these, including Java, ECMAScript, C# and Python (with __str__(self)defined). The same applies to other functions like ceil(), floor() etc.

答:
Suppose we're designing a new language and we want Sqrt to be an instance method.  So we look at the double class and begin designing.  It obviously has no inputs (other than the instance) and returns a double.  We write and test the code.  Perfection.

But taking the square root of an integer is valid, too, and we don't want to force everyone to convert to a double just to take a square root.  So we move to int and start designing.  What does it return?  We could return an int and make it work only for perfect squares, or round the result to the nearest int (ignoring the debate about the proper rounding method for now).  But what if someone wants a non-integer result?  Should we have two methods - one that returns an int and one that returns a double (which is not possible in some languages without changing the name).  So we decide that it should return a double.  Now we implement.  But the implementation is identical to the one we used for double.  Do we copy-and-paste?  Do we cast the instance to a double and call that instance method?  Why not put the logic in a library method that can be accessed from both classes.  We'll call the library Math and the function Math.Sqrt.

Why is Math.Sqrt a static function?:

Because the implementation is the same regardless of the underlying numeric type

Because it does not affect a particular instance (it takes in one value and returns a result)

Because numeric types do not depend on that functionality, therefore it makes sense to have it in a separate class

We haven't even addressed other arguments:

Should it be named GetSqrt since it returns a new value rather than modifying the instance?

What about Square? Abs? Trunc? Log10? Ln? Power? Factorial? Sin? Cos? ArcTan?

Title: Why is Math.Sqrt() a static function?


问:
Who should read Exception.Message if at all?
When designing exceptions should I write messages that a user or a developer should understand? Who should actually be the reader of exception messages?

I find exception messages aren't useful at all and I always have a hard time writing them. By convention the type of the exception should already tell us why something didn't work and custom properties might add even more information like file names, indexes, keys etc. so why repeating it in the message itself? An autogenerated message could also do and all what it had to contain is the name of the exception with a list of additional properties. This would be exactly as useful as a handwritten text.

Wouldn't it be better to not write messages at all but instead have special exception renderers that takes care of creating meaningful messages maybe in different languages rather then hardcoding them in code?

I've been asked whether either of those questions provide an answer to my question:

How to write a good exception message

Why do many exception messages not contain useful details?

I've read them both and I wasn't happy with their answers. They talk about users in general and focus on the content of the message itself rather then on the addressee and it turns out there can be at least two of them: the end-user and the developer. I never know which one I should speak to when writing exception messages.

I even think that the famous message doesn't have any real value at all as it just repeats the name of the exception type in different words so why bother writing them at all? I can perfectly generate them automatically.

To me exception message lacks a differentiation of its readers. A perfect exception would need to provide at least two versions of the message: one for the end-user and one for the developer. Calling it just a message is too generic. A developer message should be then written in English but the end-user's message might need to be translated into other languages. It is not possible to achieve all this with only one message so an exception would need to provide some identifier to the end-user message that as I just said, might be available in different languages.

When I read all the other linked questions I get the impression that an exception message is indeed intended to be read by an end-user and not a developer... a single message is like to have a cake and eat it too.

答:
Those messages are for other developers

Those messages are expected to be read by developers to help them debug the application. This can take two forms:

Active debugging. You're actually running a debugger while writing code and trying to figure out what happens. In this context, a helpful exception will guide you by making it easy to understand what's going wrong, or eventually suggesting a workaround (although this is optional).

Passive debugging. The code runs in production and fails. The exception is logged, but you only get the message and the stack trace. In this context, a helpful exception message will help you quickly localize the bug.

Since those messages are often logged, it also means that you shouldn't include sensitive information there (such as private keys or passwords, even if it could be useful to debug the app).

For instance, IOSecurityException type of an exception thrown when writing a file is not very explicit about the problem: is it because we don't have permissions to access a file? Or maybe we can read it, but not write? Or maybe the file doesn't exist and we don't have permissions to create files there? Or maybe it's locked (hopefully, the type of the exception will be different in this case, but in practice, types can sometimes be cryptic). Or maybe Code Access Security prevents us from doing any I/O operation?

Instead:

IOSecurityException: the file was found but the permission to read its contents was denied.

is much more explicit. Here, we immediately know that permissions on the directory are set correctly (otherwise, we won't be able to know that the file exists), but permissions at file level are problematic.

This also means that if you cannot provide any additional information which is not already in the type of the exception, you can keep the message empty. DivisionByZeroException is a good example where the message is redundant. On the other hand, the fact that most languages let you throw an exception without specifying its message is done for a different reason: either because the default message is already available, or because it will be generated later if needed (and the generation of this message is enclosed within the exception type, which makes perfect sense, "OOPly" speaking).

Note that for technical (often performance) reasons, some messages end up being much more cryptic than they should be. .NET's NullReferenceException:

Object reference not set to an instance of an object.

is an excellent example of a message which is not helpful. A helpful message would be:

Object reference product not set to an instance of an object when called in product.Price.

Those messages are not for end users!

End users are not expected to see exception messages. Never. Although some developers end up showing those messages to the users, this leads to poor user experience and frustration. Messages such as:

Object reference not set to an instance of an object.

mean absolutely nothing to an end user, and should be avoided at all costs.

The worst case scenario is to have a global try/catch which throws the exception to the user and exits the app. An application which cares about its users:

Handles exceptions in the first place. Most ones can be handled without disturbing the user. Network is down? Why not wait for a few seconds and try again?

Prevents a user from leading the application to an exceptional case. If you ask the user to enter two numbers and divide the first one by the second one, why would you let the user to enter zero in the second case in order to blame him a few seconds later? What about highlighting the text box in red (with a helpful tool tip telling that the number should be different than zero) and disabling the validation button until the field remains red?

Invites a user to perform an action in a form which is not an error. There are no enough permissions to access a file? Why not ask the user to grant administrative permissions, or pick a different file?

If nothing else works, shows a helpful, friendly error which is specifically written to reduce user's frustration, help the user to understand what went wrong and eventually solve the problem, and also help him prevent the error in the future (when applicable).

In your question, you suggested to have two messages in an exception: a technical one for developers, and the one for end users. While this is a valid suggestion in some minor cases, most exceptions are produced at a level where it is impossible to produce a meaningful message for the users. Take DivisionByZeroException and imagine that we couldn't prevent the exception from happening and can't handle it ourselves. When the division occurs, does the framework (since it's the framework, and not business code, which throws the exception) know what will be a helpful message for a user? Absolutely not:

The division by zero occurred. [OK]

Instead, one can let it throw the exception, and then catch it at a higher level where we knew the business context and could act accordingly in order to actually help the end user, thus showing something like:

The field D13 cannot have the value identical to the one in field E6, because the subtraction of those values is used as a divisor. [OK]

or maybe:

The values reported by ATP service are inconsistent with the local data. This may be caused by the local data being out of sync. Would you like to synchronize the shipping information and retry? [Yes] [No]

Those messages are not for parsing

Exception messages are not expected to be parsed or used programmatically either. If you think that additional information can be needed by the caller, include it in the exception side by side with the message. This is important, because the message is subject to change without notice. Type is a part of the interface, but the message is not: never rely on it for exception handling.

Imagine the exception message:

Connecting to the caching sever timed out after waiting for 500 ms. Either increase the timeout or check the performance monitoring to identify a drop in server performance. The average wait time for caching server was 6 ms. for the last month, 4 ms. for the last week and 377 ms. for the last hour.

You want to extract the “500”, “6”, “4” and “377” values. Think a bit about the approach you will use to do the parsing, and only then continue reading.

You have the idea? Great.

Now, the original developer discovered a typo:

```<code>Connecting to the caching sever timed out after waiting [...]
</code>```

should be:

```<code>                            ↓
Connecting to the caching server timed out after waiting [...]
</code>```

Moreover, the developer considers that month/week/one hour are not particularly relevant, so he also does an additional change:

The average wait time for caching server was 6 ms. for the last month, 5 ms. for the last 24 hours and 377 ms. for the last hour.

What happens with your parsing?

Instead of parsing, you could be using exception properties (which can contain whatever one wants, as soon as the data can be serialized):

{
    message: "Connecting to the caching [...]",
    properties: {
        "timeout": 500,
        "statistics": [
            { "timespan": 1, "unit": "month", "average-timeout": 6 },
            { "timespan": 7, "unit": "day", "average-timeout": 4 },
            { "timespan": 1, "unit": "hour", "average-timeout": 377 },
        ]
    }
}
```

How easy is to use this data now?

Sometimes (such as within .NET), the message can even be translated into user's language (IMHO, translating those messages is absolutely wrong, since any developer is expected to be able to read in English). Parsing such messages is close to impossible.

Body:
Those messages are for other developers

Those messages are expected to be read by developers to help them debug the application. This can take two forms:

Active debugging. You're actually running a debugger while writing code and trying to figure out what happens. In this context, a helpful exception will guide you by making it easy to understand what's going wrong, or eventually suggesting a workaround (although this is optional).

Passive debugging. The code runs in production and fails. The exception is logged, but you only get the message and the stack trace. In this context, a helpful exception message will help you quickly localize the bug.

Since those messages are often logged, it also means that you shouldn't include sensitive information there (such as private keys or passwords, even if it could be useful to debug the app).

For instance, IOSecurityException type of an exception thrown when writing a file is not very explicit about the problem: is it because we don't have permissions to access a file? Or maybe we can read it, but not write? Or maybe the file doesn't exist and we don't have permissions to create files there? Or maybe it's locked (hopefully, the type of the exception will be different in this case, but in practice, types can sometimes be cryptic). Or maybe Code Access Security prevents us from doing any I/O operation?

Instead:

IOSecurityException: the file was found but the permission to read its contents was denied.

is much more explicit. Here, we immediately know that permissions on the directory are set correctly (otherwise, we won't be able to know that the file exists), but permissions at file level are problematic.

This also means that if you cannot provide any additional information which is not already in the type of the exception, you can keep the message empty. DivisionByZeroException is a good example where the message is redundant. On the other hand, the fact that most languages let you throw an exception without specifying its message is done for a different reason: either because the default message is already available, or because it will be generated later if needed (and the generation of this message is enclosed within the exception type, which makes perfect sense, "OOPly" speaking).

Note that for technical (often performance) reasons, some messages end up being much more cryptic than they should be. .NET's NullReferenceException:

Object reference not set to an instance of an object.

is an excellent example of a message which is not helpful. A helpful message would be:

Object reference product not set to an instance of an object when called in product.Price.

Those messages are not for end users!

End users are not expected to see exception messages. Never. Although some developers end up showing those messages to the users, this leads to poor user experience and frustration. Messages such as:

Object reference not set to an instance of an object.

mean absolutely nothing to an end user, and should be avoided at all costs.

The worst case scenario is to have a global try/catch which throws the exception to the user and exits the app. An application which cares about its users:

Handles exceptions in the first place. Most ones can be handled without disturbing the user. Network is down? Why not wait for a few seconds and try again?

Prevents a user from leading the application to an exceptional case. If you ask the user to enter two numbers and divide the first one by the second one, why would you let the user to enter zero in the second case in order to blame him a few seconds later? What about highlighting the text box in red (with a helpful tool tip telling that the number should be different than zero) and disabling the validation button until the field remains red?

Invites a user to perform an action in a form which is not an error. There are no enough permissions to access a file? Why not ask the user to grant administrative permissions, or pick a different file?

If nothing else works, shows a helpful, friendly error which is specifically written to reduce user's frustration, help the user to understand what went wrong and eventually solve the problem, and also help him prevent the error in the future (when applicable).

In your question, you suggested to have two messages in an exception: a technical one for developers, and the one for end users. While this is a valid suggestion in some minor cases, most exceptions are produced at a level where it is impossible to produce a meaningful message for the users. Take DivisionByZeroException and imagine that we couldn't prevent the exception from happening and can't handle it ourselves. When the division occurs, does the framework (since it's the framework, and not business code, which throws the exception) know what will be a helpful message for a user? Absolutely not:

The division by zero occurred. [OK]

Instead, one can let it throw the exception, and then catch it at a higher level where we knew the business context and could act accordingly in order to actually help the end user, thus showing something like:

The field D13 cannot have the value identical to the one in field E6, because the subtraction of those values is used as a divisor. [OK]

or maybe:

The values reported by ATP service are inconsistent with the local data. This may be caused by the local data being out of sync. Would you like to synchronize the shipping information and retry? [Yes] [No]

Those messages are not for parsing

Exception messages are not expected to be parsed or used programmatically either. If you think that additional information can be needed by the caller, include it in the exception side by side with the message. This is important, because the message is subject to change without notice. Type is a part of the interface, but the message is not: never rely on it for exception handling.

Imagine the exception message:

Connecting to the caching sever timed out after waiting for 500 ms. Either increase the timeout or check the performance monitoring to identify a drop in server performance. The average wait time for caching server was 6 ms. for the last month, 4 ms. for the last week and 377 ms. for the last hour.

You want to extract the “500”, “6”, “4” and “377” values. Think a bit about the approach you will use to do the parsing, and only then continue reading.

You have the idea? Great.

Now, the original developer discovered a typo:

Connecting to the caching sever timed out after waiting [...]

should be:

                            ↓
Connecting to the caching server timed out after waiting [...]

Moreover, the developer considers that month/week/one hour are not particularly relevant, so he also does an additional change:

The average wait time for caching server was 6 ms. for the last month, 5 ms. for the last 24 hours and 377 ms. for the last hour.

What happens with your parsing?

Instead of parsing, you could be using exception properties (which can contain whatever one wants, as soon as the data can be serialized):

{
    message: "Connecting to the caching [...]",
    properties: {
        "timeout": 500,
        "statistics": [
            { "timespan": 1, "unit": "month", "average-timeout": 6 },
            { "timespan": 7, "unit": "day", "average-timeout": 4 },
            { "timespan": 1, "unit": "hour", "average-timeout": 377 },
        ]
    }
}

How easy is to use this data now?

Sometimes (such as within .NET), the message can even be translated into user's language (IMHO, translating those messages is absolutely wrong, since any developer is expected to be able to read in English). Parsing such messages is close to impossible.

ContentLicense: CC BY-SA 4.0


答:
Mathematical operations are often very performance-sensitive. Therefore, we will want to use static methods that can be fully resolved (and optimizied, or inlined) at compile time. Some languages do not offer any mechanism to specify statically dispatched methods. Furthermore, the object model of many languages has considerable memory overhead that is unacceptable for “primitive” types such as double.

A few languages allow us to define functions that use method invocation syntax, but are actually dispatched statically. Extension methods in C# 3.0 or later are an example. Non-virtual methods (e.g. the default for methods in C++) are another case, though C++ does not support methods on primitive types. You could of course create your own wrapper class in C++ that decorates a primitive type with various methods, without any runtime overhead. However, you will have to manually convert values to that wrapper type.

There are a couple of languages that do define methods on their numeric types. These are usually highly dynamic languages where everything is an object. Here, performance is a secondary consideration to conceptual elegance, but those languages are not generally used for number crunching. However, these languages might have an optimizer that can “unbox” operations on primitives.

With the technical considerations out of the way, we can consider whether such a method-based math interface would be a good interface. Two issues arise:

mathematical notation is based on operators and functions, not on methods. An expression such as 42.sqrt will appear much more alien to many users than sqrt(42). As a math-heavy user, I'd rather prefer the ability to create my own operators over dot-method-call syntax.

the Single Responsibility Principle encourages us to limit the number of operations that are part of a type to the essential operations. Compared with multiplication, you need the square root remarkably rarely. If your language is specifically intended for statistical anlysis, then providing more primitives (such as operations mean, median, variance, std, normalize on numeric lists, or the Gamma function for numbers) can be useful. For a general-purpose language, this just weighs down the interface. Relegating non-essential operations to a separate namespace makes the type more accessible for the majority of users.

Title: Why is Math.Sqrt() a static function?

Body:
In a discussion about static and instance methods, I always think, that Sqrt() should be a instance method of number types instead of a static method. Why is that? It obviously works on a value.

```<code> // looks wrong to me
 var y = Math.Sqrt(x);
 // looks better to me
 var y = x.Sqrt();
</code>```

Value types obviously can have instance methods, as in many languages, there is an instance method ToString().

To answer some questions from the comments: Why should 1.Sqrt() not be legal? 1.ToString() is.

Some languages do not allow to have methods on value types, but some languages can. I am talking about these, including Java, ECMAScript, C# and Python (with __str__(self)defined). The same applies to other functions like ceil(), floor() etc.


问:
Should API DTOs be shaped to client(s) or be universal?
I have a project with an internal desktop client app and a server-side client API service talking to a relational database. I seem to have two choices:

1) shape DTOs to client views, e.g. AccountOverviewInfoDto and AccountFullDetailsDto for a master-detail GUI scenario:

+ optimal amount of data is transferred;

+ server-side database queries are more optimal;

+ less object conversions/mappings are needed (domain -> DTO);

- DTOs are coupled to different client GUI paradigms (desktop large screen vs mobile small screen);

- client API is coupled to the client app in terms of changes and deployment.

2) make DTOs "universal" by keeping them close to domain model and then shape them to GUI via viewmodel objects:

- non-optimal amount of data is transferred;

- server-side database queries are less optimal;

- more object conversions/mappings are needed (domain -> DTO -> viewmodel).

+ DTOs are decoupled from different client GUI paradigms (desktop large screen vs mobile small screen);

+ client API is decoupled from the client app in terms of changes and deployment.

What is the best practice if there is any? Are there any other choices?

答:
Make sure you're optimizing the right thing.

If you were writing an MMO, shaving a second off transfer times or a couple bytes off some data might be significant.

For a company-internal app, the most critical resource is your time.  If you go with your option 2 (universal DTOs that are not specific to a view) you'll stand a better chance of writing the code once.

If you go with your option 1 (DTOs "tuned" for a specific view), you'll be constantly coming back to this code to write more / tweak the ones you have / add fields / remove fields, and so on.

I strongly recommend you keep the code simple and short (which means generic DTOs) until specific testing has proved that you actually have a performance problem.


问:
Difference between Software Engineering and IT?
I see mostly everyone distinguishes between being a Software Engineer and being in IT on the jobs sections of their site. What are the definitions of each, and the distinction between them?</p>

答:
IT is a department within a company like Human Resources or Marketing.  This covers the backbone in a sense of some companies as what a company uses is maintained by IT.  This includes a bunch of analysts, developers and administrators that create and manage systems.

Software Engineering in contrast has the narrower focus of how to create the abstract set of instructions used in building various systems.  Note that the software can have various purposes as it could be a game, operating system, or part of something used to run a business.

As an example, where I work there are at least a couple of different sets of software engineers:  Product Development and Information Systems.  The latter is what most would call IT while the former is the group that helps design and build the software the company sells to customers.  My work in IS tends focus on systems that others within the company will use rather than products or services the company sells to the public.  Hopefully that provides a bit more clarity.

OwnerDisplayName: Jungle Hunter


问:
Switch complex WinForms app to WPF MVVM
This question is connected with my older question C# Application GUI design dependent on configuration.

I have built quite big WinForms application working in industry for a few years. It communicates with many HW devices. Application can be configured to use or not use some of these devices and GUI is modified by this configuration. Now, even more devices (and application possible configurations) are going to be added, so I need to refactor whole application, maybe even write the most of it again and it will be very painful work as it was generally my the first bigger project.

Finally, I decided to start learning WPF and I'm going to rewrite this application again using WPF, partly because I feel that such complex WinForms application isn't easily extensible and maintainable, partly because I want to learn WPF anyway in the future.

I want to use it properly and separate business logic from UI. I came across some MVVM tutorials using WPF, but all of them are very simple. My application has quite complex menus, few DataGridViews, and PixtureBox, which I'm drawing some measured 2-D stuff onto.
As I said, application communicates a lot with several devices as well as  with SQL server both-sided, and of course it has many threads. Also, there is quite a lot of miscellaneous dialogs.
At this moment in WinForms version, it's mess of logic and UI mixed together.

Can you suggest me any approach, how to start separating logic from UI in such kind of complex project?

I've read many WPF/MVVM tutorials, but all examples are simple, of course, and I'm not able to think in MVVM enough yet.

答:
It's the same approach as with any other major refactoring.

Built unit tests to validate the behavior of the existing code.

Identify and isolate small sections of code that can be refactored.

Refactor one section at a time.

Verify that all unit tests (see step 1) continue to pass.  If they fail, fix your refactoring.

Rinse and repeat until you regret the day you ever decided to refactor the code base.

Eventually you'll complete the refactoring.  Swear off code-behind and promise yourself that you'll never, ever make those mistakes again.

As far as how to separate out business logic from UI logic within MVVM.  For the most part, all of your business logic should live at your Model layer or lower.  All UI related logic, including properties to be bound to, will live at the View and ViewModel layer.

A good rule of thumb on "Is it business logic or UI logic" is the following.  If the behavior of the code should persist regardless of what the UI is, that's business logic.  If the code's behavior is tied to the presentation of the data, that's UI logic.

Title: Switch complex WinForms app to WPF MVVM