问:
Is this data model a list or tree?
Using python syntax with below environment diagram, teacher taught us that there are 11 trees(orange boundary) in this diagram, including leaf.

It has been taught here,

lists are represented as a row of index-labeled adjacent boxes, one per element. Each box either contains a primitive value or points to a compound value. For example:

```<code>nested_list = [   [1, 2],    [],     [[3, False, None],[4, lambda : 5]]   ]
</code>```

tree is either a single value called a leaf or a sequence of trees. Typically some type restriction is placed on the leaves. E.g a tree of numbers. For example:

```<code>tree = [     [1, [2], 3, []],      [[4], [5,6]],       7    ]
</code>```

My question:

In general, Can a tree have heterogeneous type data? for example: Can I say, abc = [1, 2, 3, 4, lamda: 5] a tree with 5 leaves?

Note: Intention is to understand, whether tree can have heterogeneous type data

答:
This heavily depends on definition of list and tree.

Mathematically list doesn't mean anything and tree is just special subset of a graph.

Inferring from your question, your teacher's definition of tree is nested lists. In which case, list of nesting depth of 0 is still a tree. So

abc = [1, 2, 3, 4]

Is a tree.

In this case, the list is subset of tree. Every list is a tree, but not every tree is a list. If you have operation that only works on list, then only instances that are lists can be used as parameter, but not when they are just tree.

At least that's how it would work in math. In case of this python "pseudoexample" there is not really much difference between tree and a list. I believe you are getting confused, because your teacher is just using Python structures as definitions and not defining the terms in unambiguous mathematical terms.

Title: Is this data model a list or tree?


问:
Banning zero-argument functions -- what problems could it cause in a hypothetical language?
I'm creating a programming language as a hobby, but I encountered a problem with designing its syntax. The problem is the conflict between the syntax for defining zero-argument functions and the syntax for reassignment operations. The function definition syntax is taken from Haskell, and looks like this:

```<code>name arguments = expression
</code>```

A zero-argument function would obviously have this form: name = expression. However, that poses a problem because, without context, the programmer could confuse such a definition with a reassignment operation (which has the same form, variable = expression).

My solution is simple: ban functions with zero arguments. More precisely, such functions would now take a single value of the unit type as their argument. This is inspired by Scala, where functions that "don't return anything", actually return () (of type Unit), which is a type with only one possible value that carries no useful information.

The definition would then look like this:

```<code>name () = expression
</code>```

And a call would have the form name () -- note that '()' is not a parameter list, but rather the value of type Unit. The above definition relies on pattern-matching, as () is not the name of the argument, but the only form it can take.

My question is whether such a design decision makes theoretical sense, and whether it would have some practical negative effects?

答:
I have decided to go through with this design decision for the following reasons:

Such a convention is actually more consistent with the functional nature of the language. All functions are unary (accept a single argument) -- those accepting multiple arguments are simply curried, and those accepting "none" (as per this decision) actually accept the sole () value.

Several functional languages already implement this convention, such as Ocaml (see the section How to define a procedure?), which gave me more confidence that it's not just a random hack I came up with.

The decision itself allows for the interesting Haskell-inspired function definition syntax to be used, because the ambiguity between reassignment is removed (which is the original motivation for the decision, see the question).

So the direct answer to the question is it doesn't not make sense theoretically, and has positive practical effects.

ContentLicense: CC BY-SA 3.0


问:
What is a good way for Tomcat to interact with another Java application running on the local machine
I'm new to using Java within a web environment. At the moment I have a Java application that we run on a local machine, we'll call it the server app. We want to add the ability to communicate with this application by means of a RESTful interface.

I've been playing around with Tomcat and Glassfish and I have something that sort of works, but I'm certain I'm doing things in a weird way. I have a listener in the web application that creates an instance of my server application every time Tomcat is started.

When a connection is created the servlet grabs the instance of this server application so I can interact with it and pass data to a jsp. I can't help but feel this isn't a conventional approach.

I'm leaning towards just running the server jar entirely separately and using sockets on the local machine for the servlets to interact, but I can't help but think this is overkill. I've looked around and it looks like RMI might be a solution, but I'm unfamiliar with it.

Here is what I need to be able to do:

Tomcat needs to be running to accept REST requests

I need a way for the web application to check to see if the server app is running

I need the web app to be able to get an instance of the server app so that I can call it's methods or at least send it some JSON

Overall I think it's a fairly basic task, I'm just getting a bit lost trying to find a good way to organize my project.

Should I run the server app outside of the Tomcat environment and just use sockets and some JSON?

Should I run the server app outside of Tomcat and use RMI (will require some research, but that's no big deal)

Should I keep the server app within the Tomcat environment like I have it currently?

答:
The easiest approach if you can accept the drawbacks is to have tomcat as a passive server such that it never contacts the server app. All data flows the other way by periodicly sending heart beats to tomcat and retrieve the json data you mentioned. The drawbacks is that it will (only) be eventual consistent so you will have to accept a small time delay.

The other approach is hosting a server in the server app. This can be a RMI server or a http server. Since java SE 6 there have been a http server built into java which is fairly easy to work for posting documents back and forth. There is no templating or all that stuff, but just serialize your data to JSON and you are good to go. Once you have this server running just connect to it from the tomcat server.


问:
COM - with great power comes great responsibility, but at what cost? (looking for advice on coding practices when working with COM)
What is best (or commonly accepted) practice for where to declare COM object variables (scope) and how to handle cleaning them up when using structured error handling?

I just spend a whole load of time learning about Garbage Collection and Reference Counting and dealing with releasing COM objects in .NET.

Working with COM is annoying...

The Dilemma

I realize it's important to release referenced COM objects after finishing with them.  I also realize it's also important to anticipate and handle errors.

These two things together seem to be at odds with what keeps getting beaten into my head as best practice:  declaring your variables where they are used.

Now, in order to ensure the references are released when done with them, it seems to make the most sense to do this cleanup within the Finally portion of a Try/Catch block.

However, doing so means that I cannot declare these variables within the Try or Catch portions of the block because they will not be accessible to the Finally portion.

SO....

Where does that leave me with regards to following best practices?

Should I continue to declare variables at the beginning of each routine in order to clean them up using Finally?

Is there some other method of accessing COM references at the end of a procedure?

Am I just picking pepper out of fly shit with regards to best practices?

Example Code

In Example 1, I've declared all my variables before entering the Try/Catch block.  This way I can ensure they get cleaned up, regardless of any errors.

In Example 2, I've declared my variables where they are used, but this causes a problem with potential non-release of COM objects.

```<code>Imports System.Runtime.InteropServices

Module COMexamples

    Sub Example1()
        Dim Com1 As SomeCOM
        Dim Com2 As AnotherCOM
        Try
            Com1 = New SomeCOM
            Com1.DoSomeStuff()
        Catch ex As Exception
            Com2 = New AnotherCOM
            Com2.CleanupTheMess()
        Finally
            If Not Com1 Is Nothing Then
                Com1.Close()
                Marshal.FinalReleaseComObject(Com1)
            End If
            If Not Com2 Is Nothing Then
                Com2.Quit()
                Marshal.FinalReleaseComObject(Com2)
            End If
        End Try
    End Sub

    Sub Example2()
        Try
            Dim Com1 As New SomeCOM
            Com1.DoSomeStuff()
            'If an exception is thrown, the object won't get released!
            Com1.Close()
            Marshal.FinalReleaseComObject(Com1)
        Catch ex As Exception
            Dim Com2 As New AnotherCOM
            Com2.CleanupTheMess()
            'Another exception here means we miss releasing this COM reference too!
            Com2.Quit()
            Marshal.FinalReleaseComObject(Com2)
        Finally
            'This is pretty much useless now as Com1 and Com2 are out of scope here
        End Try
    End Sub
End Module
</code>```

答:
You should declare and create the object before the try-block. This is not specifically for com, but a general principle when using a resource that must explicitly be deallocated in a finally block.

In other words - first create the resource, and if that succeeds you try to use the resource. On the other hand, if resource allocation fails, the try/finally block is never executed.

This also relieves you from checking if Com1 or Com2 is assigned in the finally block - you know for sure that if you enter the try block that the object has been initialized.

```<code>Sub Example()
    Dim Com1 As New SomeCOM
    Try
        Com1.DoSomeStuff()
    Catch
        Cleanup()
    Finally
        Com1.Close()
        Marshal.FinalReleaseComObject(Com1)
    End Try
End Sub

Sub Cleanup()
    Dim Com2 As New AnotherCOM
    Try
        Com2.CleanUpTheMess()
    Finally
        Com2.Quit()
        Marshal.FinalReleaseComObject(Com2)
    End Try
End Sub
</code>```

Body:
You should declare and create the object before the try-block. This is not specifically for com, but a general principle when using a resource that must explicitly be deallocated in a finally block.

In other words - first create the resource, and if that succeeds you try to use the resource. On the other hand, if resource allocation fails, the try/finally block is never executed.

This also relieves you from checking if Com1 or Com2 is assigned in the finally block - you know for sure that if you enter the try block that the object has been initialized.

Sub Example()
    Dim Com1 As New SomeCOM
    Try
        Com1.DoSomeStuff()
    Catch
        Cleanup()
    Finally
        Com1.Close()
        Marshal.FinalReleaseComObject(Com1)
    End Try
End Sub

Sub Cleanup()
    Dim Com2 As New AnotherCOM
    Try
        Com2.CleanUpTheMess()
    Finally
        Com2.Quit()
        Marshal.FinalReleaseComObject(Com2)
    End Try
End Sub


问:
Git Repository Setup
I am moving my companys source control from TFS to GIT.
We have TFS currently defined as.

Project Collection /

/ Client A

/ Product A

/ Product B

/ Product C

/ Client B

/ Product D

/ Product E

/ Product F

What is the best way to do this in Git? I have thought about the following:

Repository (Client A)

Branch (Product A)

Branch (Product B)

Branch (Product C)

Repository (Client B)

Branch (Product D)

Branch (Product E)

Branch (Product F)

What do you think is the best approach as the design is slightly different?

答:
At our company, we develop all source code from one large repository with individual folders for each client/product. Although clients each receive their own individualized software package, all our products have our expertise in common and we re-use much of our code. This re-use happens through shared libraries. Having all client projects in the same repository allows to fulfill all the necessary library dependencies.

Even if at this point in time all your software products are distinct and non-overlapping, code re-use and shared libraries may come in the future. This extension will be very easy in a single repository, but more intricate with multiple.

Title: Git Repository Setup


问:
How to approach legacy code? Desperate case
I have a methodological question. I am faced with a reasonably large legacy system (Java Enterprise). I am new to its codebase -as everybody in the team- since it's a product we had in outsourcing that the business people decided to bring in-house because it became business-critical.

The current state of the project is:

There is nobody available who worked on that system (except one senior dev), this implies we have little knowledge about how actually the system internally works.

The codebase is very poorly engineered (no tests at all, poor or even non-existent OO design)

Architecture is convoluted and not very well documented

It integrates with a lot of third party components/systems

It's business critical (operates 24/7 also processing financial transactions).

We are scared of doing any modifications because, without a proper testing coverage, we do not know if we break things. Remember that money is involved.

No proper unit-testing is possible since there is no OO design. Only black-box integration testing is somehow feasible (be aware about the convoluted synch and asynch interactions it has with third-party systems like payments services).

Poor OO design makes difficult to identify, isolate and factor-out single features of the system.

The question is: how would you approach the re-engineering of this monster? We would like to gain confidence about its internals, definitely improve its OO design and testability....but how to safely start?

Ideally we should be an agile team but with this starting point is am not sure about the best way to approach this problem. So far we started adding few integration tests, but in any case we are not confident about any move we take....We don't have any oracle/document that tell us if we are breaking things.

答:
I've been in a similar situation, we ended up saving all input and output files to/from the system in production. With them in hand we could build a test setup and have a test harness (did running the input files still give the same output files).

Then we could slowly start to refactor and uncover what the system requirements actually were and in the end rewrite major parts.


问:
Is async keyword an ultimate replacement for asyncio module?
Recently, there was a rise of interest toward asynchronous programming in Python community.  First prominent expression of this interest was the appearance of Asyncio —codenamed Tulip— framework [PEP 3156] in the standard library, and then, after a couple of years, the capability to write async code was introduced to the core of the language through async def construction [PEP 0492].

Some core developers who participated in designing Asyncio claim that the latter will actually benefit from async keyword introduction [Andrew Svetlov on Google Plus].  From my perspective, though, it seems like async brings pretty much the same functionality as Asyncio does.  Perhaps it's just me missing something.

So, the question is, shall async take over Asyncio, or they are really that much different?

Was Asyncio just a playground before async has been approved?

Otherwise, how can Asyncio leverage the new async powers of the language?

答:
asyncio is a set of libraries. The PEP and implementation define event loop abstractions, protocols for tasks to interact with the event loop, and various I/O classes and concurrency primitives that can be used in asynchronous code. The way to write these tasks is/was to write a generator and the way to wait on the completion of another task is/was to yield from that_task.

aync extends the language with a different way to write generators (here called coroutines to avoid confusion) that is similar but more powerful and useful for writing asynchronous tasks with asyncio (and other, similar event loops). await is like yield from conceptually and in practice. The async PEP does not define any APIs (except the bare bones to support the new built-in type), and does not affect the asyncio API at all. It's simply a better way to use asyncio.


问:
Delete unused source code from the repository or keep an archive folder?
At our company, we have a single version control repos with a structure like this:

```<code>/client1_product
/client2_product
/...
/shared_lib1
/shared_lib2
/...
</code>```

After almost two decades of development, this list has become long and confusing, mixing active projects with those long dead. Orientation is difficult for newcomers. We are discussing two options.

Delete old elements:

Makes clear this is never to be touched again.

Everything is, of course, still retrievable through version control.

Moving old elements to an 'archive' folder:

Out of sight, but still in reach.

For some, this is not good enough.

How can we improve the clarity within our repos?

答:
The problem with deleting is that they are "out of sight" and therefore "out of mind". The problem with archiving is that links or relative references will no longer apply. Tricky...

Personally I would delete them, and tag the revisions that these were deleted. This allows the dead projects to be easily retrieved, in place, yet also be hidden but still known about. Add a description for each of the dead projects so someone knows what they did, if they do decide to look for old code to resurrect or build from.


答:
Since the history is preserved in version control, there is absolutely no reason not to remove code you don't need. By the way, this applies as well to commented code within the source: don't comment blocks of code, just remove them; if you'll need them later, version control is your friend.

Later may be even in an hour. The common sense may dictate that if you think you'll need a whole project or a piece of code in an hour, then it's better to keep it or comment it. I would discourage such practice, since reverting removed elements should be a matter of seconds anyway (especially since you remember exactly what was removed). Moving project to archive directory, and then moving it back will take the same amount of time then reverting. As for the commented code, there is a huge risk that you'll end up forgetting to remove it if it appears that you actually don't need it.

Removing entire projects is especially important for persons who join the project. In SVN, for example, the new person has to checkout the last revision to get the source code, which means downloading even archived projects. This can impact the time wasted doing the original checkout, time you can considerably reduce by simply removing the projects you don't need, instead of moving them to a specific directory.

To ensure optimal performance of your team, make sure that:

The version control history will remain forever. I've seen many cases where teams migrate to a different version control and don't bother migrating the history (although it's relatively easy to do). There was also one case where the team decided to remove the old revisions to free some disk space on their server (yes, I know, you find that extremely stupid too).

Message logs are explicit enough and commits are granular enough to be able to quickly find the removed code when needed. Tagging might be used for that (although I'm personally against such usage, including in this particular case).

Developers, especially newcomers, know how to use history and how to get back the removed code properly. The worst case is someone who doesn't know how to do that and will copy-paste code by hand and then commit.

The major problem with that is that version control doesn't know that the code already existed; this decreases the traceability (it's like all this code was written from scratch) and increases the disk usage footprint (since the version control should store the code instead of just referring to an older commit).

Title: Delete unused source code from the repository or keep an archive folder?

Body:
At our company, we have a single version control repos with a structure like this:

```<code>/client1_product
/client2_product
/...
/shared_lib1
/shared_lib2
/...
</code>```

After almost two decades of development, this list has become long and confusing, mixing active projects with those long dead. Orientation is difficult for newcomers. We are discussing two options.

Delete old elements:

Makes clear this is never to be touched again.

Everything is, of course, still retrievable through version control.

Moving old elements to an 'archive' folder:

Out of sight, but still in reach.

For some, this is not good enough.

How can we improve the clarity within our repos?


问:
Is Haskell's type system an obstacle to understanding functional programming?
I'm studying Haskell for the purpose of understanding functional programming, with the expectation that I'll apply the insight that I gain in other languages (Groovy, Python, JavaScript mainly.)

I choose Haskell because I had the impression that it is very purely functional, and wouldn't allow for any reliance on state.

I did not choose to learn Haskell because I was interested in navigating an extremely rigid type system.

My question is this:  Is a strong type system a necessary by-product of an extremely pure functional language, or is this an unrelated design choice particular to Haskell?

答:
It tells you right away when you make dumb mistakes.  This is helpful.
I have been working in Racket (Scheme) this last term, and there have been a number of times where I have passed an unparsed s-exp where I expected a parsed ast to some function in my interpreter, and it only showed up in my medium sized test suite.  If I had some static typing, it would have been an brought to my attention right away.

Of course, logic errors can't really be caught by the type system, but the number of ways in which you can screw up is greatly diminished.

As well, type inference lets you ignore the type system if you wish.  It's still there, but it doesn't require active input on your part.  It's still helpful to understand the types of your functions, but correct code will work fine.

Haskell's purity is encoded in its type system.  The IO monad is a type level construct that stops impure code from leaking into pure functions, so the purity is guaranteed by the type system.


问:
BDD, Cucumber best practices
I'm trying to understand some best practices when it comes to BDD and Cucumber. I've only recently started to use it,
and the first feature I have written a test for is testing a search feature, more specifically how a Repository layer
integrates with a JPA EntityManager that has been injected using the @PersistenceContext annotation. It does this by
creating an EJBContainer using the GlassFish embedded maven dependency and initialising the persistence layer this way.
It works so I'm fairly happy with that.

Now I'm at the stage where I want to start using Selenium with Cucumber to test the search feature of the JSF page. Which
I'm assuming I'll be able to check the contents of a HTML table after the search has been submitted.

Is it possible to use the same feature file with a different steps class that does Selenium testing? Is this a good practice?
At the moment none of this Cucumber stuff feels like unit testing, it all feels like Integration testing!

What I have in mind is something like the following organisation

```<code>test
    |
    java
    |   |
    |   feature
    |       |
    |       web
    |       |  |
    |       |  user
    |       |      UserSearchWebSteps
    |       |      UserAddWebSteps
    |       |      UserDeleteWebSteps
    |       |      UserWebTest
    |       db
    |          |
    |          user
    |              UserSearchDBSteps
    |              UserAddDBSteps
    |              UserDeleteDBSteps
    |              UserDBTest
    resources
        |
        feature
            |
            user
                search_users.feature
                add_user.feature
                delete_user.feature
</code>```

So the steps would be organised at the level of web or db, and then in this example each user step is under that. With
a corresponding runner test class that runs all those steps

And as both the web and db levels expect the same results I'd have shared feature files.

The UserXXXTest would then specify in it's cucumber options where to find the feature file, and because the steps for web
and db are separated at the pacakge level having a step method with the same regexp shouldn't be an issue.

```<code>@RunWith(Cucumber.class)
@CucumberOptions(features =
{
    "src/test/resources/feature/user"
})
public class UserDBTest
{

}
</code>```

答:
Traditionally in BDD we'd start with the outside and move in, so we'd have a web page, then from there move to the actual DB connections until the scenario worked with the web page.

However, your question about whether you can use the same feature file with different steps at different levels is appropriate and applicable.

I don't think at the moment that Cucumber actually does this. Behat for PHP does. Konstantin Kudryashov's post on how to model the domain using the same end-to-end scenarios that work through the web layer may give you some ideas about how to do this kind of thing well (short version: remember to make your scenarios declarative!)

If you wanted to do it in Cucumber, I think it might be possible if you used symbolic links to mirror the feature files that you wanted to run in both places? You'll need some jiggery-pokery to get it to work. But... the theory is very sound, and Konstantin who's a well-respected BDD community member has been exploring this space for a while.

Even at lower levels, though, it wouldn't be a unit test, but an integration test.

It is possible to use BDD at a unit level (it started there, after all) but you'd probably want to use something like RSpec rather than the heavier-weight system-level frameworks.

Title: BDD, Cucumber best practices


问:
Is using up 'too much' storage space a practical concern when storing only text in a database in 2015?
I originally started writing a question on StackOverflow about a clever way to optimise keeping a version history of large text fields in a relational database table, possibly by using deltas instead of incurring the storage cost of a full copy of the changed text in an audit table on each update, which is regularly suggested as the simplest way to keep version history in a database.

As I was writing it, I began to wonder, what exactly do I mean by incur the storage cost, really?

I've read in a few places on the internet that the complete works of Shakespeare uncompressed comes to around 5Mb, so assuming that's true, 1TB could hold roughly 200,000 copies.

That is a big book, with a lot of text in it. 200,000 is a lot of copies of that book. A 1TB spinning disk will not exactly break the bank these days, either.

When we're talking about text in a database in 2015, is it wasted effort to think about compression, optimisation, or even deliberately minimising inputs, or is storage cheap enough now that I'm never going to have to care about hitting an upper limit, in practice, and I should instead optimise for app code and schema simplicity?

答:
I do not have enough brownie points to comment so I will leave an answer.

Keep in mind that the works of Shakespeare were written by a single human for human consumption. I think you should expand your horizons a little and consider machine generated text of which humans are only intended to read parts of.

For example, looking inside the /var/log/ directory of an active web server will show you a realistic example of text file sizes spiralling quickly out of control. So much so that people tend to install daemons which will compress and rotate log files on a regular basis.

If you have ever played with a network analysis tool such as tcpdump, again you will start gobbling up 10s or even 100s of Gigabytes of disk space in a matter of hours if you try to capture all HTTP traffic flowing across an active network.

So yes, depending on where the text is coming from, the disk space used by a text only database can be substantial, even in 2015.


问:
Is the function using python list comprehension, stateless?
Below is the function count_leaf, that appends mutable list branch_counts, which is not stateless.

```<code>def count_leaf(tree):
    if is_leaf(tree):
        return 1
    branch_counts = list()
    for b in tree:
        branch_counts.append(count_leaf(b))
    return sum(branch_counts)
</code>```

Below is the program that uses list comprehension.

```<code>def count_leaves(tree):
    if is_leaf(tree):
        return 1
    else:
        branch_counts = [count_leaves(b) for b in tree]
        return sum(branch_counts)
</code>```

Is the function count_leaves using list comprehension [count_leaves(b) for b in tree] purely functional?

答:
Yes it is, because there is no state being mutated. The line branch_counts = [count_leaves(b) for b in tree] can be interpreted as a simple binding (like a let statement in Haskell or Lisp), as there are no further reassignments or mutations.

Additionally, you could reformat it like this to make it clearer:

```<code>def count_leaves(tree):
    return 1 if is_leaf(tree) else sum([count_leaves(b) for b in tree])
</code>```

Body:
Yes it is, because there is no state being mutated. The line branch_counts = [count_leaves(b) for b in tree] can be interpreted as a simple binding (like a let statement in Haskell or Lisp), as there are no further reassignments or mutations.

Additionally, you could reformat it like this to make it clearer:

def count_leaves(tree):
    return 1 if is_leaf(tree) else sum([count_leaves(b) for b in tree])


问:
Advantage of non-deterministic staistical analysis?
I am working with a Java Library used for identifying the language of a given text.  It relies on an n-gram analysis of the text to return a set of languages it might be and the "confidence" that it is that language.

I wrote a wrapper class to run it, however, it is non-deterministic (results are generally incorrect with <200 chars input, don't worry about that):

```<code>C:\wamp\www\langdetect [master]> java Detect viking rowboat
af:0.8571411945873898 lt:0.1428569473433962
C:\wamp\www\langdetect [master]> java Detect viking rowboat
af:0.5714268373011915 sw:0.2857137271014559 lt:0.14285898741269984
C:\wamp\www\langdetect [master]> java Detect viking rowboat
af:0.9999958253321346
</code>```

The analysis is non-deterministic by default (can be made deterministic like so: https://code.google.com/p/language-detection/issues/detail?id=64) but my question is this:

Is there any advantage to this analysis being non-deterministic?

The only upside I can think of is that a deterministic algorithm will, statistically, be incorrect a percentage of the time (even with valid input), while non-deterministic removes this guarantee (but still is incorrect sometimes).  Does this even make sense?

答:
Usually the benefit from using non-deterministic algorithms is simple: Runtime.

It is often used in Monte-Carlo algorithms, which basically try a predefined number of possibilities (i.e. "Is this text German?" - "No", "Is this text spanish?" - "No", "Well, no idea then".). While the deterministic solution would be to try every single possibility, which is sometimes unfeasable.

However, this is not the case in your example. In your library a set of random numbers is generated from a seed. If this seed is computed randomly, you ralgorithm is non-deterministic and will produce different results for different runs.

If your seed is constant (in this example it would be zero) however, it will produce the same result every run. This does not only not improve the result, but it also removes one important advantage: The more often you run the non-deterministic program, the better your results will become. This does not apply to the deterministic approach.

So, why should you use the deterministic approach then? One example I can think of is testing. Unit tests on random results are pretty much the biggest pain you can experience. Imagine you make a change in one part of the program and for some reason your unit-test fails. You run it again and it fails again. So you start digging, where there is nothing to find.

TL;DR:

If you want good results: Run your non-deterministic program (possibly multiple times).

If you want reproducable results (e.g. Testing): Use the deterministic approach.

OwnerDisplayName: Will


问:
Can I use GPL, LGPL, MPL licensed packages with my application and make it closed source?
I saw a company is using BusyBox and also using Gpl + Lgpl + Mpl packages on it, and then they have there own application running on it. Their application is a closed source package.

You buy the device but its closed source. How come GPL mixed with LGPL+MPL becomes closed source?

I thought the rule is?? Or I am wrong or this following info is wrong?:

GPL: If you use it in your application then you must release your application under the GPL. That doesn't mean you can't also sell it (like they sell Linux CD's) but you must also release the source code for free. That might work for you, but probably not.

LGPL: If you use it in your application then you can still have a closed source proprietary licensed application. But if you modify the LGPL library then you must release your modifications under the LGPL, even though your application can remain closed source.

答:
(This answer was not intended for this question, but for a more specific one about git, and covers its specific case in greater detail than this question would practically allow. See comment 599873 for more info. It'll stay here in this form at least until the matter is resolved.)

Git is covered by GPLv2.

Generally, if you have any questions on FSF's licensing, the way to go is

the license itself (it's not some doorstopper and is quite conprehensible. The time invested in learning it will repay tenfold.)

do keep in mind though that for GPLv2 (as opposed to v3), a few terms are taken from the US law and thus aren't defined in the text. (Indeed, they also turned out to mean slightly different things in different jurisdictions, but FSF didn't report this to be a serious problem)

FSF FAQ on their licenses, specifically, a FAQ on GPLv2,

other related materials on the web, including FSF facilities; watch for their authority though

as a last resort (short of a lawyer), FSF itself (they aren't a law firm, of course, so they will only give you general commentary without regard to jurisdiction - as are they free to ignore a request. My practice says they do reply to reasonable inquiries that are not already answered elsewhere, although it can take a while).

In your case, the related materials are:

GPLv2#section2:

b) You must cause any work that you distribute or publish, that in
  whole or in part contains or is derived from the Program or any part
  thereof, to be licensed as a whole at no charge to all third parties
  under the terms of this License.

  <...>

  These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.

  Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.

  In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.

GPLv2 FAQ #NFUseGPLPlugins:

It depends on how the program invokes its plug-ins. If the program
  uses fork and exec to invoke plug-ins, then the plug-ins are separate
  programs, so the license of the plug-in makes no requirements about
  the main program.

So, you cannot make your work "contain" git but you can include it as a separate entity that your work uses. VMWare's example shows that the latter includes packaging it into the distribution or a compound file within the distribution (an ISO image it was).

What's the distinction? It took me a while to come to a conclusion. In the end, the paragraph "it is not the intent... to claim rights... rather... to control the distribution of derivative or collective works based on the Program" convinced me that the distinction is if the resulting work is considered a derivative of the GPL'ed part under copyright law. With this last one, GPL can't help you - you need to consult applicable copyright law or follow in another's footsteps.

Specifically, VMWare Server's example shows that it's okay to include the object code into your distribution and

install it alongside your program

pack it into a compound file within its footage if it's clearly a compound file and can be taken apart with widely available tools (an ISO image)

However, you cannot distribute the source inside your installer - unless users have no problem taking it apart, too


问:
How to model a time-based m-to-n relationship in Entity Framework using code first
I have to model and manage a time-based configuration. Typically - without an OR mapper - I would start with the database tables.

```<code>Screen            Color        ColorScreenMapping
-------------     ----------   --------------------------------------------
id | name         id | name    valid_from | screen_id | color_id | disabled
1  | screen 1     1  | red     1.1.2015   | 1         | 1        | 0
2  | screen 2     2  | green   3.1.2015   | 1         | 2        | 0
3  | screen 3     3  | blue    7.1.2015   | 1         | 3        | 0
                               1.1.2015   | 2         | 1        | 0
                               5.1.2015   | 2         | 2        | 0
                               9.1.2015   | 2         | 2        | 1
</code>```

Then I would model two classes: Screen and Color. The database query would ensure that for a given date each screen has exactly one color object associated (1-N relation).

The downside would be that changes to the configuration would only be possible at the database level and not in the C # model. (There would be no valid_from property in the model.)

How would a suitable model look like for the code-first approach?

Would it be wiser to start with my database and use the db-first approach?

答:
If you want to have a valid_from property in C#, then you should model it in C#.

You suggest an implementation and conclude what requirements could (and could not) be fulfilled with this implementation. That puts the cart before the horse. Start with your requirements, then come up with an implementation.

How would a suitable model look like for the code-first approach?

This depends on what you want to do with that model. What information do you need in C#? A model that is suitable will contain all that information.

Maybe you only want to retrieve the current screen-color mapping. In this case C# needs no valid_from, because this information is implicitely gien by when the request to the DB is made.

Maybe you want to add new screen-color mapping from C# to the DB. In this case, you need to explicitly specify the value of valid_from for each new entry and you should model it in C#.


答:
In this case you can pretend that it is, but be careful. List comprehentions create or mutate variables in the surrounding scope. (in ipython console):

```<code>In [1]: x
NameError: name 'x' is not defined

In [2]: [x for x in range(10)]
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [3]: x
Out[3]: 9
</code>```

So if you had something like

```<code>x = "foo"
[x for x ...]
</code>```

x will not be "foo" any more.

Note that this doesn't happen when using generator expressions:

```<code>In [4]: y
NameError: name 'y' is not defined

In [5]: (y for y in range(10))
Out[5]: <generator object <genexpr> at 0x7f55b7861e10>

In [6]: y
NameError: name 'y' is not defined

In [7]: y = "foo"

In [8]: y
Out[8]: 'foo'

In [9]: (y for y in range(10))
Out[9]: <generator object <genexpr> at 0x7f55b7877410>

In [10]: y
Out[10]: 'foo'
</code>```

edit: Forgot to actually answer the question clearly. No, it is not stateless, it mutates state locally.

Title: Is the function using python list comprehension, stateless?

Body:
Below is the function count_leaf, that appends mutable list branch_counts, which is not stateless.

```<code>def count_leaf(tree):
    if is_leaf(tree):
        return 1
    branch_counts = list()
    for b in tree:
        branch_counts.append(count_leaf(b))
    return sum(branch_counts)
</code>```

Below is the program that uses list comprehension.

```<code>def count_leaves(tree):
    if is_leaf(tree):
        return 1
    else:
        branch_counts = [count_leaves(b) for b in tree]
        return sum(branch_counts)
</code>```

Is the function count_leaves using list comprehension [count_leaves(b) for b in tree] purely functional?

Body:
In this case you can pretend that it is, but be careful. List comprehentions create or mutate variables in the surrounding scope. (in ipython console):

In [1]: x
NameError: name 'x' is not defined

In [2]: [x for x in range(10)]
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [3]: x
Out[3]: 9

So if you had something like

x = "foo"
[x for x ...]

x will not be "foo" any more.

Note that this doesn't happen when using generator expressions:

In [4]: y
NameError: name 'y' is not defined

In [5]: (y for y in range(10))
Out[5]: <generator object <genexpr> at 0x7f55b7861e10>

In [6]: y
NameError: name 'y' is not defined

In [7]: y = "foo"

In [8]: y
Out[8]: 'foo'

In [9]: (y for y in range(10))
Out[9]: <generator object <genexpr> at 0x7f55b7877410>

In [10]: y
Out[10]: 'foo'

edit: Forgot to actually answer the question clearly. No, it is not stateless, it mutates state locally.


问:
Looking for an Appropriate Search Algorithm
I am currently planning an upcoming project and am looking for an algorithm for searching a database.

The search is as follows;
There will be some specifically labelled criteria (or fields) and I would like to find any objects in which its fields match the specified criteria. As well as this it needs to rank partial results based on the number matches for each field.

Heres an example -

```<code>Person 1
Name: John
Occupation: Developer
Favourite Colour: Blue

Person 2
Name: John
Occupation: Manager
Favourite Colour: Blue

Person 3
Name: John
Occupation: Developer
Favourite Colour: Green

Person 4
Name: Larry
Occupation: Mailman
Favourite Colour: Red

Search Criteria
Name: John
Occupation: Developer
Favourite Colour: Blue

Results

Rank 1
Person 1

Rank 2
Person 2
Person 3
</code>```

The ranks would not be visible but would handle the order of the result list.

I could do this quite easily for a small data set, for example, JavaScript;

results = [];
for(var i = 0; i < objects.length; i++) {
  var result = _.intersection(criteria, object[i]);
  if(result.length > 0) {
    object[i].rank = result.length;
    results.push(object[i])
  }
}
return results (and order by rank)
```

Obviously this won't work when querying a db but I am hoping someone much smarter than me can point me in the right direction.
I feel like there must be a solution to this out there and it's probably simple but my Google-fu is failing me.

答:
Well, do you or don't you have the data in a normal database? If you do, there is no way around querying all possible matches from the data base (with a long query full of OR operators) and then sorting the result however you see fit. In other words, you're not looking for a search algorithm, but for sorting functions.

You can only solve this problem with special algorithms if you are willing to adapt the format in which you store data to your requirements. For instances data warehouses are frequently denormalized so that you can query individual sales, but also aggregate sales, and even find months with total sales in a particular range.

It's possible to do something similar for your problem by precomputing scores that express how well a record matches a query and then querying that index for good scores rather than all records for their individual fields. However, that only works well when you have particular queries that you will pose again and again, because each query defines its own particular match score. Your example looks as if you can generate many different, in fact arbitrary queries. That will probably require more effort in indexing than you save in retrieving.


问:
How to handle OSS license on GitHub with non-OSS pictures
I am working on an app that will be open-sourced and published on GitHub. But, the problem is, that the graphics my client gives me contains some in-house characters that the company owns. We have a deal that the code will be MIT or Apache 2.0, but how do I handle the images? Do I have to omit their upload on GitHub or can I include two license files? Or what should I do?

答:
I wouldn't "pollute" your OSS repo with some proprietary files, its a bit like uploading your OSS code with an Amazon API key or config file with your system's passwords in them.

So you have to find some way to manage the distinction, probably the easiest is to create a new, private, repo for the images or create an archive of them and copy these to the right place as a manual step after getting the OSS source.

Alternatively, put the private images in a different directory, one that is configurable in your app, so you can hold them separately - check out the OSS files and it will reference the special images because they always exist on your system, but not on anyone else who clones the project.

Depending on the app, you might like to deliver some OSS placeholders for these images so anyone who gets your project will not be left with broken image links (assuming they are part of the project and not some config)


问:
Isn't there a substantial problem with SVN tags?
A common practice for SVN tags is to tag different releases in order to be able to find them with ease later. As I understand it, tagging is the same thing as branching, that is in two cases, it just creates a copy of the trunk in a separate directory (would it be branches/something or tags/1.2.3), which means that:

There is no impact on the amount of data stored by SVN itself (excluding a few bytes which indicate that a specific tag corresponds to a specific revision). If the dump was 800 MB without the tag, it will still be 800 MB plus a few bytes with the new tag.

Files are duplicated on disk when checked out. A project which takes 30 MB on disk will take 60 MB once the tag is created.

It means that:

Once I create a tag, every developer of my team will get a lot of data from SVN the next time he will update.

With dozens or hundreds of tags (like it's usually the case when tagging every release), checkouts can take hours even for a small project.

Isn't that problematic? Couldn't it implemented differently, for instance through svn propedit? Are there valid cases where it makes sense to checkout every tag, instead of just one?

Note: as someone who uses continuous deployment consistently, I never used tags in practice, since every commit is potentially deployed in production if it passes the tests. This means that I may have missed something fundamental about tags or their internals, and I'm sorry if this is the case. My interest towards tags rises from the fact that I spent the last two hours checking out a third-party small project which has over two hundred tags.

答:
Why would it be a problem over having trunk and branches?
A tag is just another branch, but (and perhaps this is the important bit) you do not have to checkout the entire SVN repo.

Instead of calling svn co http://repo/ call svn co http://repo/trunk
Then, if you want to see a particular branch use svn switch.

Everyone I know who uses the trunk/tags/branches repo setup will checkout trunk or a branch as the root. Doing this, they will never see the other branches or tags unless they use svn switch to swap the view of the repo to that root.

What you describe is even more a problem with git as it checks out the entire repo and then presents you with a view of it based on a single branch or master. All the files are present (but hidden 'underneath' the current view), so technically SVN is superior to git in this regard (ie being able to partially checkout a fraction of a repo is particularly good when you multi-gigabyte repositories).

You don't need to use tags if you don't want to, they are only a marker in the repo anyway, being a cheap copy of the trunk that you have tagged. You could, if you preferred, remember the revision number (as this is a globally unique value) for the revision you tagged, but there is no way in SVN to mark a revision number with some human-readable moniker.


问:
What false ideas are there that puts people off using threads?
Implementing threading in a program is hard, yes, however why is it that some people will not implement them even when there is an obvious need for it.

An example: Program has to load a dataset from a database, the thing to do would be to make the connection and get the data from the database in a worker thread and then load it into the GUI, leaving the GUI thread responsive for the user.

But no, I've talked to people whom seem to think that threads are evil and bad and whatnot and one should avoid them at all costs.  I've even heard that some class instructor advised against to use of threads and therefore did not want cover their use. WHAT???

With the hardware going into multi-core, I think that we need to understand threads better and not be afraid to use them. I find it a fascinating subject personally.

So what are things you've heard about threading that are false?

答:
To summarize point wise why threads are difficult to use :-

True  Things
1) Need the synchronization, and careful design decisions about what to lock and when to lock

2) No control on the run time flow

3) Difficult debugging

4) (Very few times) platform compatibility :- Libraries do exists to take care of this

False Things : -

1) Confusing concepts of thread-safe and re-entrant functions

2) Threads looks good on the paper but are very hard to implement

ContentLicense: CC BY-SA 2.5


问:
Const C++ DRY Strategies
For avoiding non-trivial C++ const related duplication, are there cases where const_cast would work but a private const function returning non-const wouldn't?

In Scott Meyers' Effective C++ item 3, he suggests that a const_cast combined with a static cast can be an effective and safe way to avoid duplicate code, e.g.

```<code>const void* Bar::bar(int i) const
{
  ...
  return variableResultingFromNonTrivialDotDotDotCode;
}
void* Bar::bar(int i)
{
  return const_cast<void*>(static_cast<const Bar*>(this)->bar(i));
}
</code>```

Meyers goes on to explain that having the const function call the non-const function is dangerous.

The code below is a counter-example showing:

contrary to Meyers's suggestion, sometimes the const_cast combined with a static cast is dangerous

sometimes having the const function call the non-const is less dangerous

sometimes both ways using a const_cast hide potentially useful compiler errors

avoiding a const_cast and having an additional const private member returning a non-const is another option

Are either of the const_cast strategies of avoiding code duplication considered good practice?  Would you prefer the private method strategy instead?  Are there cases where const_cast would work but a private method wouldn't?  Are there other options (besides duplication)?

My concern with the const_cast strategies is that even if the code is correct when written, later on during maintenance the code could become incorrect and the const_cast would hide a useful compiler error.  It seems like a common private function is generally safer.

```<code>class Foo
{
  public:
    Foo(const LongLived& constLongLived, LongLived& mutableLongLived)
    : mConstLongLived(constLongLived), mMutableLongLived(mutableLongLived)
    {}

    // case A: we shouldn't ever be allowed to return a non-const reference to something we only have a const reference to

    // const_cast prevents a useful compiler error
    const LongLived& GetA1() const { return mConstLongLived; }
    LongLived& GetA1()
    {
      return const_cast<LongLived&>( static_cast<const Foo*>(this)->GetA1() );
    }

    /* gives useful compiler error
    LongLived& GetA2()
    {
      return mConstLongLived; // error: invalid initialization of reference of type 'LongLived&' from expression of type 'const LongLived'
    }
    const LongLived& GetA2() const { return const_cast<Foo*>(this)->GetA2(); }
    */

    // case B: imagine we are using the convention that const means thread-safe, and we would prefer to re-calculate than lock the cache, then GetB0 might be correct:

    int GetB0(int i) { return mCache.Nth(i); }
    int GetB0(int i) const { return Fibonachi().Nth(i); }

    /* gives useful compiler error
    int GetB1(int i) const { return mCache.Nth(i); } // error: passing 'const Fibonachi' as 'this' argument of 'int Fibonachi::Nth(int)' discards qualifiers
    int GetB1(int i)
    {
      return static_cast<const Foo*>(this)->GetB1(i);
    }*/

    // const_cast prevents a useful compiler error
    int GetB2(int i) { return mCache.Nth(i); }
    int GetB2(int i) const { return const_cast<Foo*>(this)->GetB2(i); }

    // case C: calling a private const member that returns non-const seems like generally the way to go

    LongLived& GetC1() { return GetC1Private(); }
    const LongLived& GetC1() const { return GetC1Private(); }

  private:
    LongLived& GetC1Private() const { /* pretend a bunch of lines of code instead of just returning a single variable*/ return mMutableLongLived; }

    const LongLived& mConstLongLived;
    LongLived& mMutableLongLived;
    Fibonachi mCache;
};

class Fibonachi
{
    public:
      Fibonachi()
      {
        mCache.push_back(0);
        mCache.push_back(1);
      }

      int Nth(int n)
      {
        for (int i=mCache.size(); i <= n; ++i)
        {
            mCache.push_back(mCache[i-1] + mCache[i-2]);
        }
        return mCache[n];
      }

      int Nth(int n) const
      {
          return n < mCache.size() ? mCache[n] : -1;
      }
    private:
      std::vector<int> mCache;
};

class LongLived {};
</code>```

答:
When implementing const and non-const member functions that only differ by whether the returned ptr/reference is const, the best DRY strategy is to:

if writing an accessor, consider whether you really need the accessor at all, see cmaster's answer and http://c2.com/cgi/wiki?AccessorsAreEvil

just duplicate the code if it is trivial (e.g. just returning a member)

never use a const_cast to avoid const related duplication

to avoid non-trivial duplication, use a private const function returning a non-const that both the const and non-const public functions call

e.g.

```<code>public:
  LongLived& GetC1() { return GetC1Private(); }
  const LongLived& GetC1() const { return GetC1Private(); }
private:
  LongLived& GetC1Private() const { /* non-trivial DRY logic here */ }
</code>```

Let's call this the private const function returning non-const pattern.

This is the best strategy for avoiding duplications in a straight forward fashion while still allowing the compiler to perform potentially useful checks and report const related error messages.

Title: Const C++ DRY Strategies

Body:
When implementing const and non-const member functions that only differ by whether the returned ptr/reference is const, the best DRY strategy is to:

if writing an accessor, consider whether you really need the accessor at all, see cmaster's answer and http://c2.com/cgi/wiki?AccessorsAreEvil

just duplicate the code if it is trivial (e.g. just returning a member)

never use a const_cast to avoid const related duplication

to avoid non-trivial duplication, use a private const function returning a non-const that both the const and non-const public functions call

e.g.

public:
  LongLived& GetC1() { return GetC1Private(); }
  const LongLived& GetC1() const { return GetC1Private(); }
private:
  LongLived& GetC1Private() const { /* non-trivial DRY logic here */ }

Let's call this the private const function returning non-const pattern.

This is the best strategy for avoiding duplications in a straight forward fashion while still allowing the compiler to perform potentially useful checks and report const related error messages.

ContentLicense: CC BY-SA 4.0


问:
How to use Messagequeing in a distributed web application
I am curious for solutions to this problem:

Assume we are going to build an online-store. To better scale parts of the architecture, it is broken into independend subsystems. The typical scenario would involve an application server (or something similar), where the requests from clients come in.

The flow for a login would be something like this:

Request comes in

->Authenticate user

->Get last products a user bought

->calculate appropriate ads

->deliver generated Page to client.

This is less efficient, because the queries of the subsystems happen in a serial/synchronous way. It would be better, to make calls in parallel.

For example one could use a Node.JS server and call the subsystems asynchronously. On callback there is something like a "reduce function" called, which aggregates all data and, when all data is collected, it sends the generated page back to the client.

So this system seems more efficient.

Another step would include further decoupling and introduces message queues.

So there is on the one side the application server, which gets the requests and serves the replys; and on the other hand, the independend components communicating over message queues.

The flow would be the following:

Incoming Request

->Message: "User with session key 1234567890 is granted access"

So with the session key, the user and according messages are identifyable.
This message is taken by the user-service and produces the answer "User with session key 1234567890 is John Doe from New York". This message is published to all the other services in the application. So they can react and publish their results.

My Problem is, how do I route the result back to the application server which has to wait an unknown amount of time?
How does it know, when to collect all the results for its request?

One solution could be, using an in memory database (e.g. Redis). All services could write their results into Redis, which is constantly polled by the application server while waiting for a result to deliver. But, is that the solution?

Are there other solutions?

答:
In the example you use there is nothing that can be parallelized. Each step requires data from the previous. Hope you are using better example for your design drafts.

The direction in which you are heading requires quite elaborate orchestration (as you have realized yourself) and this is non-trivial problem. One possible technical option is to use temporary queues — the front server creates temporary destination for the user session, then provides it as reply destination to the sub-tasks. This type of solution requires lots of care around the handling of the destination life cycle — thinking about timeouts, abandoned sessions, dangling temporary destinations, as well as fail over on the coordinator side (the front server). Hypothetically you can build tree of steps using this pattern but be very careful to control the interaction complexity.

Broadcasting (in it's broad meaning) in highly distributed system with expected high load is to be avoided. You will have to factor in some natural (hence cheap) partitioning in the message stream designs. Example of such partitioning is the round-robbin queue behavior in the mainstream JMS brokers.

I would definitely not broadcast the authentication attempt as this is gonna be very easy to be abused by DOS attack.

Alternative would be to render placeholders in the webpage for each portlet (advertisements, recent purchases, so on) that request the data on page load and leave the orchestration to the browser. It is so simple that no other solution beats it's cost/benefit ratio.

I am not sure how relevant this is — be careful to know very well why you are cutting the system in the particular way you have chosen. The boundaries of a service is extremely important decision because if done wrong it has long lasting negative effect and it's very hard to be fixed. If you haven't done it before, invest the time to research the SOA literature on methodologies for defining service boundaries. Regardless of the technology you plan to use.


问:
Interfaces, abstraction, coding to an interface
Original question here

I am learning OOP and SOLID. I have a 'main' class that performs some actions after reading variables from a config file. This 'main' class is not the focus of this question but it can be described as a concretion.

I am trying to split up the process of reading the config file and using its settings in the 'main' class.

I am thinking of making a Config class.

```<code>interface ConfigInterface {
    public function getFileContents();
}

class Config implements ConfigInterface {
    protected $file_path;
    protected $file_contents;

    public function getFileContents() {
        return $this->file_contents;
    }

    protected function readFileContents() {
        $file_path = $this->file_path;
        if ( is_file( $file_path ) ) {
            $file_contents = include( $file_path );

            return $file_contents;
        } else {
            die( 'Invalid config path specified ' . $file_path );
        }
    }

    public function __construct( $file_path ) {
        $this->file_path     = realpath( $file_path );
        $this->file_contents = $this->readFileContents();
    }
}
</code>```

This allows a user to get all the settings as a single array from the public method.

However, as a class, I can't help but feel these settings retrieved as an array should be assigned as individual properties of the object with public accessors. As such, these settings would be unique to my 'main' class. In this case, I'm thinking of extending a generic Config class with a MainConfig class which would have these specific properties / accessors in relation to my 'main' class.

```<code>interface ConfigInterface {
    // A config has a path, but doesn't need to have a public interface
    // So don't know what goes in here now
}

class Config implements ConfigInterface {
    private $file_contents;

    public function __construct( $config_path ) {}
    protected function readContents() {}
}

class MainConfig extends Config implments ConfigInterface {
    private $main_settings_one;
    private $main_settings_two;
    private $main_settings_three;

    public function getMainSettingOne() {};
    public function getMainSettingTwo() {};
    public function getMainSettingThree() {};
}
</code>```

Firstly, is this a correct approach or is it better to keep the array? Also, does an interface / base class need functions defined? Or can these be defined later?

Secondly, do I need a ConfigHandler / ConfigReader class? If my 'main' class needs the settings to work, could I just pass the config object to the 'main' class and have a function do this? Or is it a seperate responsibility of another class?

I am also learning coding to an interface. My 'main' class only works with specific settings (is this a concretion?) So if I had

```<code>class Main {
    public function __construct( ConfigInterface $config ) { // coding to interface
        $config->getMainSettingOne(); // specific functionality relating to a concretion?
    }
}

$conf = new MainConfig( $path );
$main = new Main( $conf );
</code>```

If anything but a MainConfig is passed then my 'main' class will not initialise properly. I was thinking of a 'specialised' interface, for use with my 'main' class.

```<code>interface MainConfigInterface {
    public function getMainSettingOne();
    public function getMainSettingTwo();
    public function getMainSettingThree();
}

class Config { ... }

class MainConfig extends Config implments ConfigInterface {
    private $main_settings_one;
    private $main_settings_two;
    private $main_settings_three;

    public function getMainSettingOne() {};
    public function getMainSettingTwo() {};
    public function getMainSettingThree() {};
}
</code>```

Then back in my 'main' class, I can still code to an interface?

```<code>class Main {
    public function __construct( MainConfigInterface $config ) { // coding to interface
        $config->getMainSettingOne();
}

$conf = new MainConfig( $path );
$main = new Main( $conf );
</code>```

Finally, is this the correct way to code to an interface in this regard?

答:
Firstly, is this a correct approach or is it better to keep the array?
  Also, does an interface / base class need functions defined? Or can
  these be defined later?

Yes, an interface need functions defined, if not where is the sense of having an interface?
An interface works like a contract between a consumer and his client. In this case the Main class consumes the Config class.
This contract could be:
The Main class needs that a Configuration on initialization brings the settings One and Two.

```<code>    interface ConfigInterface {
      public function getConfigOne();
      public function getConfigTwo();
    }
</code>```

(Maybe this is too rigid, because it means that your Main class only going to need two settings)

And then you can have classes that implement this interface in different ways

```<code>class StaticConfig implements ConfigInterface {
    public function getConfigOne(){
      return "configOne";
    }
     public function getConfigTwo(){
       return "configTwo";
     }
}
class DynamicConfiguration implements ConfigInterface {
   private ConfigReader reader;

   public function getConfigOne(){
        reader.readConfigurations(1);
   }
   public function getConfigTwo(){
      reader.readConfigurations(2)
   }
</code>```

If anything but a MainConfig is passed then my 'main' class will not
  initialise properly. I was thinking of a 'specialised' interface, for
  use with my 'main' class.

If you are expecting something specific you should not use an interface because you are not accepting the contract, you are excepting something that the interface can't give you. A specialised interface it's not the answer either, simply because you can write:

```<code>class Main {
    public function __construct( MainConfig $config ) {
        $config->getMainSettingOne();
}
</code>```

Your example it's too abstract because i don't how your Main class consumes the settings. It will be more than a Main class? It's for system-wide properties? or it's part of the domain model? However i wanted to answer because empty interfaces are a bad practice and should be avoided.
If you can detail a little more it would help me to bring you a better answer.

Body:
Firstly, is this a correct approach or is it better to keep the array?
  Also, does an interface / base class need functions defined? Or can
  these be defined later?

Yes, an interface need functions defined, if not where is the sense of having an interface?
An interface works like a contract between a consumer and his client. In this case the Main class consumes the Config class.
This contract could be:
The Main class needs that a Configuration on initialization brings the settings One and Two.

    interface ConfigInterface {
      public function getConfigOne();
      public function getConfigTwo();
    }

(Maybe this is too rigid, because it means that your Main class only going to need two settings)

And then you can have classes that implement this interface in different ways

class StaticConfig implements ConfigInterface {
    public function getConfigOne(){
      return "configOne";
    }
     public function getConfigTwo(){
       return "configTwo";
     }
}
class DynamicConfiguration implements ConfigInterface {
   private ConfigReader reader;

   public function getConfigOne(){
        reader.readConfigurations(1);
   }
   public function getConfigTwo(){
      reader.readConfigurations(2)
   }

If anything but a MainConfig is passed then my 'main' class will not
  initialise properly. I was thinking of a 'specialised' interface, for
  use with my 'main' class.

If you are expecting something specific you should not use an interface because you are not accepting the contract, you are excepting something that the interface can't give you. A specialised interface it's not the answer either, simply because you can write:

class Main {
    public function __construct( MainConfig $config ) {
        $config->getMainSettingOne();
}

Your example it's too abstract because i don't how your Main class consumes the settings. It will be more than a Main class? It's for system-wide properties? or it's part of the domain model? However i wanted to answer because empty interfaces are a bad practice and should be avoided.
If you can detail a little more it would help me to bring you a better answer.


问:
Is it fine to have broken intermediate commits, as long as the final commit in any push works?
Related: Should every git commit leave the project in a working state?

Suppose I make the following commits locally:

Modify the database schema, breaking the application.

Update the application so it is compatible with the database schema again.

As long as I push both commits, master remains in a working state.  However, a historical version is broken.

I'm aware that I can use git rebase -i to squash the commits together.  However, the resulting commit will be large and less descriptive.  If I need to search the commit history to find out why I changed something, I'd rather find the original commit showing what I did and why.

My questions are:

Has anyone encountered difficulties due to broken historical commits in master?

If so, is there a simple way to avoid such difficulties, without discarding individual commit messages and changes?

答:
No, it's not okay.

If you ever did a git bisect (and who doesn't love that killer feature), you know the value of a history where every commit builds.

If you have many commits during a bisect that don't build, you'll have lots of git bisect skips that make it difficult to find the last good commit.

If you finish a feature branch and merge it into master, cleanup the branch before merging so that your history is clear and building.


答:
Has anyone encountered difficulties due to broken historical commits
  in master?

Yes. Backports, reverts and bisects are harder.
So is reading the history (see below).

If so, is there a simple way to avoid such difficulties, without discarding individual commit messages and changes?

Not that I know, although branches are a decent solution.

However, I think that discarding (or rather squashing) the individual commits is the right thing to do.

During development, especially when doing TDD, committing early and often is good. You want the full trace of what you're doing so yo can backtrack, or figure out exactly when things started going wrong (or maybe you got yourself into a refactoring larger than you can chew). Commit away.

However, once a feature/change is ready to be pushed, a commit is a packaged change - ideally atomic so it can be [reviewed, rebased, merged, cherry-picked, reverted, viewed in annotate] as independently from other changes as possible.

Looking at the history of a project, a software change should be evaluated on its own. Does it build? Does it come with tests? Does it work? What does it do? What files needed to be changed to deliver that feature?

Having to assemble commits, while possible (and helped by merges), makes that harder. Therefore, I think cleaning up your history before pushing is appropriate, even if it means loosing track of how you arrived to where you are.

Title: Is it fine to have broken intermediate commits, as long as the final commit in any push works?

Body:
Related: Should every git commit leave the project in a working state?

Suppose I make the following commits locally:

Modify the database schema, breaking the application.

Update the application so it is compatible with the database schema again.

As long as I push both commits, master remains in a working state.  However, a historical version is broken.

I'm aware that I can use git rebase -i to squash the commits together.  However, the resulting commit will be large and less descriptive.  If I need to search the commit history to find out why I changed something, I'd rather find the original commit showing what I did and why.

My questions are:

Has anyone encountered difficulties due to broken historical commits in master?

If so, is there a simple way to avoid such difficulties, without discarding individual commit messages and changes?


问:
Origin of "a method should return a value or have side-effects, but not both"
I read once that a method should either have a return value (and be referentially transparent), or have side-effect(s), but not both.  I cannot find any references to this rule, but want to learn more about it.

What is the origin of this advice?  Out of what person or community did it arise?

Extra credit: What is the claimed benefit of following this advice?

答:
I don't know where it comes from, but it is good advice and fairly straight-forward to understand.

Any sanely designed program will be broken up into various parts, combined and composed in various ways. The harder it is to reason about what any particular part does, the harder it will be to make sure that your program will react in a predictable manner.

Isolating the parts that produce side-effects makes the rest easier to reason about, test, and debug. Reducing the number of side-effects in each part that does generate a side-effect will make that part easier to work with in the same manner.

If you decompose it even further, a return value is an effect. Side-effects are an effect. A function should only produce 1 effect (if possible) because the greater number of inputs and effects a function has, the greater the difficulty in reasoning about what it actually does.


答:
According to Greg Young, this idea originated from Bertrand Meyer: Command-Query separation.

It states that every method should either be a command that performs
  an action, or a query that returns data to the caller, but not both.
  In other words, Asking a question should not change the answer.1
  More formally, methods should return a value only if they are
  referentially transparent and hence possess no side effects.

1: Eiffel: a language for software engineering slide 43-48

In Domain Driven Design, this is similar to Command-Query-Read Separation/Segregation (CQRS), as named by Greg Young.

Greg Young took the idea of CQS from Bertrand to name CQRS as mentioned by Martin Fowler in this CQRS article

Benefits

The Read (Query) part can be scaled/tweaked differently from the Write (command) part. Separating the two would prevent either from getting in the way of each other when optimization/performance is key.

Read the article in the Martin Fowler link for more.

Title: Origin of "a method should return a value or have side-effects, but not both"

Body:
I read once that a method should either have a return value (and be referentially transparent), or have side-effect(s), but not both.  I cannot find any references to this rule, but want to learn more about it.

What is the origin of this advice?  Out of what person or community did it arise?

Extra credit: What is the claimed benefit of following this advice?


答:
Extra credit: What is the originally claimed benefit of following this advice?

One of the benefits of separating return value from side effects is that it removes a potential problem which may be caused by short-circuit evaluation.

bool FooWithSideEffect() {
    // do query
    // do side effect
    return resultOfQuery;
}

bool BarWithSideEffect() {
    // do query
    // do side effect
    return resultOfQuery;
}

void BadShortCircuitEvaluation()
{
    // the programmer's intent is to have side effects of both functions
    if (FooWithSideEffect() && BarWithSideEffect() ) {
        // do something
    }

    // in case FooWithSideEffect() returns true,
    // then BarWithSideEffect() is not called at all
    // because of short-circuit evaluation
}
```


问:
Testable design in Swift
I've been searching for so long about how to design testable classes in Swift but every information site just describe basic stuff like how to test, how to assert, why is testing  good...

My current design (which I'm not so sure is the best) includes a singleton ApiClient class that gets initialized on the AppDelegate. Something like this:

```<code>// Inside AppDelegate#application:didFinishLaunchingWithOptions
ApiClientFactory.make();

// Inside ApiClientFactory
static func make() {
    ApiClient.initialize(
        userProvider: UserProvider(UserLocalRepo(), UserRemoteRepo()),
        booksProvider: BooksProvider(BookLocalRepo(), BookRemoteRepo()),
        ...
    )
}
</code>```

The idea was to inject into the *Providers classes, mock repos when testing. But due to the way VCs are instantiated I'm not sure this is a good design at all, and I'm not sure where would I inject those mock repo, as it seems AppDelegate#application:didFinishLaunchingWithOptions still runs on tests (which means ApiClient will be initialized with the actual classes, not the mock ones)

答:
Singletons are a bad idea in the Apple API. Objective-C does not support singletons, instead, you create one instance that blocks the formation of any others, a crude work around IMHO, that doesn't always work. I don't think is any better in Swift and given it has to support the Objc API, I doubt it.

The preferred method to ensure a single instance is to simply place the object as a property of the app delegate. Since there is only one app and it only has one delegate and the app delegate is always alive, you get all the convenience of a singleton with none of the hassle. The "singleton" is also accessible from anywhere in the app as well since the app delegate is always accessible.

Then unit testing would proceed normally.

Title: Testable design in Swift


问:
Is there a detriment to using SQLite over a pList for persistence?
I'm making a fairly simple application and I've got a settings menu that stores times and some boolean values. I have the application storing and retrieving data already but I started to wonder if SQLite was a bad choice.

I am assuming the answer is that I should've probably just used a pList for such few values. But if I'm comfortable with CoreData (and it's already in place) is there a detriment to using SQLite over pList?

Also for sake of argument, lets say this database will hold a total of 20 items and at the most 2 tables.

答:
The difference between using plist, xml etc, and SQL whether raw or as one of the persistence options in Core Data is that the non-SQL solutions will load the entire persisted document into memory while SQL will only load what is needed at the moment.

In your case, it seems like you have so little data that SQL is over kill. You could use a plist generated from a dictionary, array etc or you could move you persistent store type to xml with Core Data.

Do make sure this is data you're persisting and not, preferences, the later should be stored in user preferences.


问:
Where to validate domain model rules that depend on database content?
I'm working on a system that allows Administrators to define Forms that contain Fields. The defined Forms are then used to enter data to the system. Sometimes the Forms are filled by a human via a GUI, sometimes the Form is filled based on values reported by another system.

For each Field, the Administrator can define a Validation Rule that limits the allowed values for the Field. The Validation Rules can be anything from "the value entered in the Field must be True or False" to "the value entered in the Field must exist in column A of table B in the database". The Administrator may at any time change the Validation Rule for the Field.

In this scenario, what in your opinion is the most suitable place for validating that each Field is filled correctly? I currently have two main approaches in mind:

Option #1: Validate in the Domain Model

Each Field object would contain the Validation Rule specified by the Administrator. The Field objects would also have a reference to an IValidator. When an attempt is made to set the value of the Field, the Field would pass the given value and the Validation Rule to the IValidator. If the given value is not valid, a ValidationException would be thrown and appropriately handled in the GUI/interface to the other system.

Pros:

Strong protection against Fields being accidentally assigned values that violate the Validation Rule

Cons:

The Data Access Layer needs to be able to bypass the validation and construct Fields that violate the current Validation Rule. Despite the Administrator changing the Validation Rule for a Field, we still need to be able to construct Field objects based on the old data e.g. when rendering a Form that was filled years ago. This could potentially be resolved by storing the current Validation Rule whenever we store the Field.

In this design, the Field model has an indirect link to the Data Access Layer/Repository via the IValidator. The injection of Services/Repositories to Domain Models seems to be generally frowned upon.

Option #2: Validate in a Service

Try to ensure that all attempts to set the value of a Field pass through a Service that ensures the Validation Rule holds. If the Validation Rule is violated, throw a ValidationException.

Of course, the Data Access Layer would not use the Service when creating Field objects that have previously been persisted in the DB.

Pros:

Does not violate the "don't inject Services/Repositories into your Domain Models"-thinking.

No need to persist the current Validation Rule when persisting the Field. The Service can simply look up the current Validation Rule for the Field; when looking at history data, the value of the Field will not be changed.

Cons:

No guarantee that all logic that should use the Service to set the Field value actually does so. I see this as a major drawback; all it seems to take is someone writing "thisField.setValue(thatField.getValue())" and the Validation Rule of thisField might be violated without anyone being the wiser. This could potentially be mitigated by ensuring that the value of the Field matches with the Validation Rule when the Data Access Layer is about to persist the Field.

I currently prefer Option #1 over Option #2, mainly because I see this as business logic and feel that Option #2 poses a greater risk of introducing bad data to the system. Which option do you prefer, or is there another design that fits this scenario better than the two options described?

Edit (Complexity of validations)

The validation cases that have come up for now are relatively simple; the Field value must be e.g. numeric, a date, a date with a time or be an existing value in a database column. However, I suspect complexity to gradually increase over time. For example, the validation solution needs to be built with internationalization in mind - things such as Dates may be input in a locale-specific syntax.

I've decided to proceed with Option #1 for now, attempting to take care not to assign too many responsibilities to the Domain Model. Those facing a similar situation may also want to check out the related questions Validation and authorization in layered architecture and Data input validation - Where? How much?.

答:
Maybe you are missing a layer. Without knowing the details of your application (requisites, architecture, etc) I would do something like
Client (whoever it be) -> Application Service -> Domain Model

The application service layer is allowed to interact with the repository and the domain model containing the business logic.
So you can have something like:

```<code>FieldUpdateService >> updateField(fieldId, newValue)
  List<FieldRule> rules = this.rulesRepository.findRulesFor(fieldId)
  Field field = this.fieldRepository.find(fieldId)
  try
    field.updateValue(rules,newValue)
    fieldRepository.save(field)
  catch
    // manage error
</code>```

If you have a relationship beteween a Field and his FieldRules and use an ORM like Hibernate in Java you will only do:

```<code>FieldUpdateService >> updateField(fieldId, newValue)
  Field field = this.fieldRepository.find(fieldId)
  try
    field.updateValue(newValue)
    fieldRepository.save(field)
  catch
    // manage error

Field >> updateValue(newValue)
  for rule in rules
     if !rule.isValid(newValue)
        throw ValueNotAllowedException
  this.value = newvalue
</code>```

Because the ORM query and instantiates the graph of objects that you ask for.

Regarding your doubt about the fact that someone can do

thisField.setValue(thatField.getValue())" and the Validation Rule of
  thisField might be violated without anyone being the wiser

Someone also could write:
FieldRule alwaysReturnTrueRule = new FieldRule{
   isValid(newValue){
     return true;
   }
}
field.updateValue("uncheckedValue",alwaysReturnTrueRule)
It's an obscure example but what im traying to say is that nothing protects you from a bad use of the code. Perhaps good documentation and comunication face to face.
I think nothing protects you from a bad use of the code.

Body:
Maybe you are missing a layer. Without knowing the details of your application (requisites, architecture, etc) I would do something like
Client (whoever it be) -> Application Service -> Domain Model

The application service layer is allowed to interact with the repository and the domain model containing the business logic.
So you can have something like:

FieldUpdateService >> updateField(fieldId, newValue)
  List<FieldRule> rules = this.rulesRepository.findRulesFor(fieldId)
  Field field = this.fieldRepository.find(fieldId)
  try
    field.updateValue(rules,newValue)
    fieldRepository.save(field)
  catch
    // manage error

If you have a relationship beteween a Field and his FieldRules and use an ORM like Hibernate in Java you will only do:

FieldUpdateService >> updateField(fieldId, newValue)
  Field field = this.fieldRepository.find(fieldId)
  try
    field.updateValue(newValue)
    fieldRepository.save(field)
  catch
    // manage error

Field >> updateValue(newValue)
  for rule in rules
     if !rule.isValid(newValue)
        throw ValueNotAllowedException
  this.value = newvalue

Because the ORM query and instantiates the graph of objects that you ask for.

Regarding your doubt about the fact that someone can do

thisField.setValue(thatField.getValue())" and the Validation Rule of
  thisField might be violated without anyone being the wiser

Someone also could write:
FieldRule alwaysReturnTrueRule = new FieldRule{
   isValid(newValue){
     return true;
   }
}
field.updateValue("uncheckedValue",alwaysReturnTrueRule)
It's an obscure example but what im traying to say is that nothing protects you from a bad use of the code. Perhaps good documentation and comunication face to face.
I think nothing protects you from a bad use of the code.


答:
Yes, you are right: Many C++ programs that attempt const-correctness are in stark violation of the DRY principle, and even the private member returning non-const is a bit too much complexity for comfort.

However, you miss one observation: code duplication due to const-correctness is only ever a problem if you are giving other code access to your data members. This in itself is in violation of encapsulation. Generally, this kind of code duplication occurs mostly in simple accessors (after all, you are handing access to already existing members, the return value is generally not the result of a calculation).

My experience is that good abstractions do not tend to include accessors. Consequently, I largely avoid this problem by defining member functions that actually do something, rather than just providing access to data members; I try to model behavior instead of data. My main intention in this is to actually get some abstraction out of both my classes and of their individual member functions, instead of just using my objects as data containers. But this style is also quite successful in avoiding the tons of const/non-const repetitive one-line accessors that are so common in most codes.

Title: Const C++ DRY Strategies

Body:
For avoiding non-trivial C++ const related duplication, are there cases where const_cast would work but a private const function returning non-const wouldn't?

In Scott Meyers' Effective C++ item 3, he suggests that a const_cast combined with a static cast can be an effective and safe way to avoid duplicate code, e.g.

```<code>const void* Bar::bar(int i) const
{
  ...
  return variableResultingFromNonTrivialDotDotDotCode;
}
void* Bar::bar(int i)
{
  return const_cast<void*>(static_cast<const Bar*>(this)->bar(i));
}
</code>```

Meyers goes on to explain that having the const function call the non-const function is dangerous.

The code below is a counter-example showing:

contrary to Meyers's suggestion, sometimes the const_cast combined with a static cast is dangerous

sometimes having the const function call the non-const is less dangerous

sometimes both ways using a const_cast hide potentially useful compiler errors

avoiding a const_cast and having an additional const private member returning a non-const is another option

Are either of the const_cast strategies of avoiding code duplication considered good practice?  Would you prefer the private method strategy instead?  Are there cases where const_cast would work but a private method wouldn't?  Are there other options (besides duplication)?

My concern with the const_cast strategies is that even if the code is correct when written, later on during maintenance the code could become incorrect and the const_cast would hide a useful compiler error.  It seems like a common private function is generally safer.

```<code>class Foo
{
  public:
    Foo(const LongLived& constLongLived, LongLived& mutableLongLived)
    : mConstLongLived(constLongLived), mMutableLongLived(mutableLongLived)
    {}

    // case A: we shouldn't ever be allowed to return a non-const reference to something we only have a const reference to

    // const_cast prevents a useful compiler error
    const LongLived& GetA1() const { return mConstLongLived; }
    LongLived& GetA1()
    {
      return const_cast<LongLived&>( static_cast<const Foo*>(this)->GetA1() );
    }

    /* gives useful compiler error
    LongLived& GetA2()
    {
      return mConstLongLived; // error: invalid initialization of reference of type 'LongLived&' from expression of type 'const LongLived'
    }
    const LongLived& GetA2() const { return const_cast<Foo*>(this)->GetA2(); }
    */

    // case B: imagine we are using the convention that const means thread-safe, and we would prefer to re-calculate than lock the cache, then GetB0 might be correct:

    int GetB0(int i) { return mCache.Nth(i); }
    int GetB0(int i) const { return Fibonachi().Nth(i); }

    /* gives useful compiler error
    int GetB1(int i) const { return mCache.Nth(i); } // error: passing 'const Fibonachi' as 'this' argument of 'int Fibonachi::Nth(int)' discards qualifiers
    int GetB1(int i)
    {
      return static_cast<const Foo*>(this)->GetB1(i);
    }*/

    // const_cast prevents a useful compiler error
    int GetB2(int i) { return mCache.Nth(i); }
    int GetB2(int i) const { return const_cast<Foo*>(this)->GetB2(i); }

    // case C: calling a private const member that returns non-const seems like generally the way to go

    LongLived& GetC1() { return GetC1Private(); }
    const LongLived& GetC1() const { return GetC1Private(); }

  private:
    LongLived& GetC1Private() const { /* pretend a bunch of lines of code instead of just returning a single variable*/ return mMutableLongLived; }

    const LongLived& mConstLongLived;
    LongLived& mMutableLongLived;
    Fibonachi mCache;
};

class Fibonachi
{
    public:
      Fibonachi()
      {
        mCache.push_back(0);
        mCache.push_back(1);
      }

      int Nth(int n)
      {
        for (int i=mCache.size(); i <= n; ++i)
        {
            mCache.push_back(mCache[i-1] + mCache[i-2]);
        }
        return mCache[n];
      }

      int Nth(int n) const
      {
          return n < mCache.size() ? mCache[n] : -1;
      }
    private:
      std::vector<int> mCache;
};

class LongLived {};
</code>```


问:
Using variable + method invocation or repeating invocation?
Here is two methods that does the same thing. One is repeating the call to the method Print where the other one does not but has an additional variable.

```<code>class Program
{
    static void Main(string[] args)
    {
        Snippet1(args);
        Snippet2(args);
    }

    private static void Snippet1(string[] args)
    {
        string message;
        if (args.Length == 0)
        {
            message = "No argument";
        }
        else
        {
            message = string.Format("Argument Count = {0}", args.Length);
        }
        Print(message);
    }

    private static void Snippet2(string[] args)
    {
        if (args.Length == 0)
        {
            Print("No argument");
        }
        else
        {
            Print(string.Format("Argument Count = {0}", args.Length));
        }
    }

    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}
</code>```

I personally do not like having the same invocation twice and prefer to use a variable which make the if statement goal to define the message instead of defining + invoking. I also believe that it's more clear to have an unique invocation if this one need to be changed later.

What is the best practice/pattern that should be applied?

答: I'd clearly choose the extra variable approach, because DRY. The varaible name additionally conveys the meaning of the argument (e.g. it could be warning or log_entry, etc).


答:
I also believe that it's more clear to have an unique invocation if this one need to be changed later.

The uniqueness of the invocation can be subject to change, too.

Maybe you don't want to print anything any more if there is no argument and you don't want to call Print at all in this case.

I don't think there is a definite answer to your question and it always depends on the specific use case.

Title: Using variable + method invocation or repeating invocation?

Body:
Here is two methods that does the same thing. One is repeating the call to the method Print where the other one does not but has an additional variable.

```<code>class Program
{
    static void Main(string[] args)
    {
        Snippet1(args);
        Snippet2(args);
    }

    private static void Snippet1(string[] args)
    {
        string message;
        if (args.Length == 0)
        {
            message = "No argument";
        }
        else
        {
            message = string.Format("Argument Count = {0}", args.Length);
        }
        Print(message);
    }

    private static void Snippet2(string[] args)
    {
        if (args.Length == 0)
        {
            Print("No argument");
        }
        else
        {
            Print(string.Format("Argument Count = {0}", args.Length));
        }
    }

    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}
</code>```

I personally do not like having the same invocation twice and prefer to use a variable which make the if statement goal to define the message instead of defining + invoking. I also believe that it's more clear to have an unique invocation if this one need to be changed later.

What is the best practice/pattern that should be applied?