问:
Is there anything inherently bad about mixing paradigms in an application?
I am currently in the process of writing a (custom) Minecraft server application in C#. I figured it's a good way to teach me a lot of important things like concurrency and especially memory efficiency (due to simply the vastness of the object space in Minecraft).

While on the train yesterday, I was finding it hard to really "think" of a way to organize the network module. I wanted a simple external interface that would give out the necessaries (Let users react to a connection being received, message being received, and when a connection is dropped). However, I also wanted it to be fairly abstract such that I could allow for either real game clients to connect or simple fake clients.

I started over-engineering things a la IConnection, INetworkModule, IConnectionFactory, IConnectionProtocol, IMessageEncoder, IMessageDecoder and so on. Kingdom of nouns galore. Not only that but I wasn't really getting anywhere - it just felt like I was putting the fundamental problem behind other layers of abstraction in that I had no idea how I wanted to organize the communication between all these modules.

Then I came to the thought - why don't I just use verbs (actions/functions/methods/whatever) instead of nouns (types) - let's focus on what I want to achieve for now, and split it up into nouns later!

And so, I came up with something similar to this:

```<code>    private static Func<IDisposable> Listen(
        Action<TcpClient> onConnectionReceived,
        Action<TcpClient> onConnectionDropped,
        Action<TcpClient, int, byte[]> onBytesReceived,
        Func<bool> isOpen)
    {
        // todo: 25565 needs to be injected
        // todo: give opportunity to supply listener
        // todo: refactor listener into role interface
        var listener = new TcpListener(IPAddress.Any, 25565);
        return () => Observable.FromAsync(listener.AcceptTcpClientAsync)
            .DoWhile(isOpen)
            .Subscribe(client =>
            {
                var stream = client.GetStream();
                // on subscribe invoke the delegate first
                onConnectionReceived(client);
                // the delegate has the option to disconnect the client
                // based on whatever criteria it see fit.
                // we should now create an observable to
                // listen for messages on this client.
                Observable.Defer(() =>
                {
                    // 8kb buffer for each connection
                    // this is actually fairly small
                    var buffer = new byte[8024];
                    // we can handle the 'doing' of things with these bytes
                    // inside the passed function. This function will be doing too much otherwise
                    return Observable.FromAsync(ct => stream.ReadAsync(buffer, 0, buffer.Length, ct))
                        .Select(n => new {Read = n, Bytes = buffer});
                }).Subscribe(a =>
                {
                    // drop connection if nothing was read
                    if (a.Read <= 0)
                        onConnectionDropped(client);
                    else
                        onBytesReceived(client, a.Read, a.Bytes);
                });
            });
    }
</code>```

Really simple. Well, I mean, not quite, but this basically does the role of all of the nouns (except IMessageEncoder/Decoder that I listed earlier), but only making assumptions of the fact that we need a TcpClient (obviously, that isn't what I want right now, but I can work to that in iteration 2!)

However, my problem with this is, is that this isn't really typical C# code.. and it surely breaks the SRP in that this function is returning a function for the entire execution of a server.

But - it makes sense to me.

So my question is, is there any real inherent downside to using a functional-esque paradigm like this as opposed to traditional Kingdom of Nouns OOP inside of C# - traditionally a multi-paradigm language? And if there are downsides, what would I face and why?

For the record, I intend for this to be OSS, so there's another issue in that some developers might not understand the code style because it's simply not OOP orientated, just pure functions.

答:
If there's something bad about mixing programming paradigms, then it's clearly lost on the C# designers; Linq is essentially a functional programming pipeline.

Clearly you already know about Steve Yegge's post, since you're referring to the Kingdom of Nouns.  Of course, the world didn't suddenly see the error of its ways and stop using Java.  Why?

Because Java is already widely used and well-understood.

Because the Kingdom of Nouns is well-suited for building data-based business systems (the efforts of Architecture Astronauts to overtake the plumbing notwithstanding).

Languages like Java have lots of ceremony like classes, interfaces, methods, scope and so on that programmers can use to understand the program's architecture.  This ceremony is largely absent in most functional languages, or at least not overtly visible.

So does that mean that you abandon functional programming altogether?  Of course not.  The lack of ceremony allows certain things to be done more quickly and more intuitively in a functional paradigm than in the Kingdom of Nouns.  This is especially true of math-like operations.

Mixing programming metaphors is a perfectly valid way to program.  Were this not true, we'd only need the One True Programming Language to Rule Them All.


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答:
C and C++ MACROS.  If I ever have to see another compiler error due to someone choosing a standard function name for their macro which screws up my code I'm going to scream.  Let's see the last offending one:

```<code>#define vector(int) new VARIANT[int];
</code>```

Aaarg!  What have you done with my STL vector!?

ContentLicense: CC BY-SA 2.5

Body:
C and C++ MACROS.  If I ever have to see another compiler error due to someone choosing a standard function name for their macro which screws up my code I'm going to scream.  Let's see the last offending one:

#define vector(int) new VARIANT[int];

Aaarg!  What have you done with my STL vector!?


问:
Google is good or bad for programmer?
Recently I was being interviewed by a company and faced one question. The interviewer asked me a question and at that time I didn't know the answer but if I had been asked about just 4 months ago, I could have answered it.

The question was from new language that I learned just 4 months ago. But I just get overview of the language and just get started working on that. Whenever I face difficultly, I google it. That means we do not have to memorize the whole programming language book! So in that situation I felt that Google screwed my job!

Not talking subjectively, Is it good to google all the time?

答:
For the most part it's good though I think it has bought about a deterioration in problem solving skills among many programmers.

Before the internet if you came up against a problem you'd not seen before you pretty much had no choice but to investigate and solve it yourself and if you couldn't come up with an answer them you had to work around them.  You could get help from team mates and from books but the total knowledge pool you had access to was perhaps a few dozen people at most.

What this meant was that pretty much every programmer who'd been working for a couple of years had experience working with genuinely detailed problems, often at a fairly low level and as a result had a far better understanding not only of how to address these problems, but of also how the language and tools worked because of their experiences.

These days most answers are available immediately as you're probably not the first person who has come across it - 30 seconds with Google will usually get you the answer.  That's obviously great - what used to take 2 days now takes 2 minutes - but I do find more and more programmers who start floundering very quickly when Google can't provide the solution because they're simply not used to it.

So overall Google has made developers way more productive but in some ways I think the big problems are bigger because less people have the experience of solving them than used to be the case.

Because of that I'd say that if you want to be a really great developer you do need to break the Google habit to an extent, if only to make sure you're capable of solving things without it when the need arises.

```#wheniwasalad```

Title: Google is good or bad for programmer?

Body:
For the most part it's good though I think it has bought about a deterioration in problem solving skills among many programmers.

Before the internet if you came up against a problem you'd not seen before you pretty much had no choice but to investigate and solve it yourself and if you couldn't come up with an answer them you had to work around them.  You could get help from team mates and from books but the total knowledge pool you had access to was perhaps a few dozen people at most.

What this meant was that pretty much every programmer who'd been working for a couple of years had experience working with genuinely detailed problems, often at a fairly low level and as a result had a far better understanding not only of how to address these problems, but of also how the language and tools worked because of their experiences.

These days most answers are available immediately as you're probably not the first person who has come across it - 30 seconds with Google will usually get you the answer.  That's obviously great - what used to take 2 days now takes 2 minutes - but I do find more and more programmers who start floundering very quickly when Google can't provide the solution because they're simply not used to it.

So overall Google has made developers way more productive but in some ways I think the big problems are bigger because less people have the experience of solving them than used to be the case.

Because of that I'd say that if you want to be a really great developer you do need to break the Google habit to an extent, if only to make sure you're capable of solving things without it when the need arises.

#wheniwasalad


答:
I believe you should be extremely careful when mixing programming paradigms in one place. The main reason is that when you mix paradigms, it will become problematic to apply "idiomatic" solutions on one paradigm to problems, that mix multiple paradigms.

I do have problem with your example, because it is not inherently functional. You could easily replace those "Actions" and "Funcs" with "Commands". It would become pure OOP code, when you start composing functions and start using higher-order functions.

Example where I found mixing to be problematic was, when once in code, we needed to "decorate" some method with pre and post-running action. The first obvious way was to create function, that would get Action, run it between pre and post code. But then, it become extremely problematic to slightly change this pre and post behavior and we had to introduce function parameters and mix multiple behaviors in single method. If we instead implemented it as class which could decorate the method, then it would be easy to use inheritance to change the pre and post actions. The slight problem with this solution is that it needs you to create a new class, which has little bit more of code than simple method.

So for me, it is great to have functional capabilities for something like LINQ, but I would think hard before using functional composition as piece of architecture or design in .NET/C# application.

I would also like to emphasize on Command pattern. I believe this pattern is heavily underappreciated and underused. Both functional and object design is all about composing behaviors. It is just that both use slightly different tools to get to the same end result. And it is probably problem of education, that many people doing OOP design don't understand that.

ContentLicense: CC BY-SA 3.0

Title: Is there anything inherently bad about mixing paradigms in an application?

Body:
I am currently in the process of writing a (custom) Minecraft server application in C#. I figured it's a good way to teach me a lot of important things like concurrency and especially memory efficiency (due to simply the vastness of the object space in Minecraft).

While on the train yesterday, I was finding it hard to really "think" of a way to organize the network module. I wanted a simple external interface that would give out the necessaries (Let users react to a connection being received, message being received, and when a connection is dropped). However, I also wanted it to be fairly abstract such that I could allow for either real game clients to connect or simple fake clients.

I started over-engineering things a la IConnection, INetworkModule, IConnectionFactory, IConnectionProtocol, IMessageEncoder, IMessageDecoder and so on. Kingdom of nouns galore. Not only that but I wasn't really getting anywhere - it just felt like I was putting the fundamental problem behind other layers of abstraction in that I had no idea how I wanted to organize the communication between all these modules.

Then I came to the thought - why don't I just use verbs (actions/functions/methods/whatever) instead of nouns (types) - let's focus on what I want to achieve for now, and split it up into nouns later!

And so, I came up with something similar to this:

```<code>    private static Func<IDisposable> Listen(
        Action<TcpClient> onConnectionReceived,
        Action<TcpClient> onConnectionDropped,
        Action<TcpClient, int, byte[]> onBytesReceived,
        Func<bool> isOpen)
    {
        // todo: 25565 needs to be injected
        // todo: give opportunity to supply listener
        // todo: refactor listener into role interface
        var listener = new TcpListener(IPAddress.Any, 25565);
        return () => Observable.FromAsync(listener.AcceptTcpClientAsync)
            .DoWhile(isOpen)
            .Subscribe(client =>
            {
                var stream = client.GetStream();
                // on subscribe invoke the delegate first
                onConnectionReceived(client);
                // the delegate has the option to disconnect the client
                // based on whatever criteria it see fit.
                // we should now create an observable to
                // listen for messages on this client.
                Observable.Defer(() =>
                {
                    // 8kb buffer for each connection
                    // this is actually fairly small
                    var buffer = new byte[8024];
                    // we can handle the 'doing' of things with these bytes
                    // inside the passed function. This function will be doing too much otherwise
                    return Observable.FromAsync(ct => stream.ReadAsync(buffer, 0, buffer.Length, ct))
                        .Select(n => new {Read = n, Bytes = buffer});
                }).Subscribe(a =>
                {
                    // drop connection if nothing was read
                    if (a.Read <= 0)
                        onConnectionDropped(client);
                    else
                        onBytesReceived(client, a.Read, a.Bytes);
                });
            });
    }
</code>```

Really simple. Well, I mean, not quite, but this basically does the role of all of the nouns (except IMessageEncoder/Decoder that I listed earlier), but only making assumptions of the fact that we need a TcpClient (obviously, that isn't what I want right now, but I can work to that in iteration 2!)

However, my problem with this is, is that this isn't really typical C# code.. and it surely breaks the SRP in that this function is returning a function for the entire execution of a server.

But - it makes sense to me.

So my question is, is there any real inherent downside to using a functional-esque paradigm like this as opposed to traditional Kingdom of Nouns OOP inside of C# - traditionally a multi-paradigm language? And if there are downsides, what would I face and why?

For the record, I intend for this to be OSS, so there's another issue in that some developers might not understand the code style because it's simply not OOP orientated, just pure functions.


问:
Real-time chat in Ruby on Rails without owning a server
I'd want to implement a Real-time chat for my Rails app but I can't really host the server which handles the sockets. I've tried Faye but it needs a server. I've also heard of pusher but it's limited to 20 users at a time on the chat and I can't really be sure they won't be more.

I've thought of IRC but I think I can't really embed it into a rails app, maybe it needs sockets...

How can I implement a real-time chat without owning a server?

答:
Web sockets are by far the most efficient way to handle chat functionalities. As a framework, Rails is not very good at handling asynchronous events and therefore establishing a socket connection to a Rails application is almost impossible. There are many solutions that are designed to handle this kind of problem. As Andrew said, Frameworks such as Node.js with Socket.IO would suffice, or, if you want to stick with Ruby, Cramp, async_sinatra, or Goliath framework are all great solutions but it would be super awesome to continue.

If you wanted to use Rails for your application's logic and also have the benefits of some kind of asynchronous event handling with publishing and subscribing you will need to use something like Private Pub Gem which is built on top of Faye and makes it dead simple to publish and subscribe to real-time events in a Rails app.

I have tried to put together a Gmail-like instant message chat application in a rails 4 app. Check out this tutorial. Hope that helps shed some light on the same.


问:
Should the commit history be used to convey critical information to developers?
During a meeting regarding the rollback of a third-party SDK from the latest version it was noted that the our developers already flagged in the commit history that the latest version should not be used.

Some developers argued that this was a bad practice and it should have instead been noted either in the source file (i.e. // Don't upgrade SDK Version x.y.z, see ticket 1234) or in a project level README file. Others argued that since the commit history is part of the project documentation it is an acceptable location for such information since we should all be reading it anyway.

Should the commit history be used to convey critical information to other developers or should such information be duplicated to another location such as a project README or comments in the relevant source file?

答:
I would say adding that type of information to a commit history is ok but it still needs to be documented properly. We recently started using confluence (by atlassian). Its searchable, you can set certain pages as favorites, etc.

Some other tools might be a public notebook in evernote or google docs.


问:
Is object oriented programming ALWAYS a good way for large projects?
Is object oriented programming always the good way for all types of projects? Is this methodology the best suited for large projects like compilers, interpreters and other large systems? Most of the compilers are written in C so I can't see any compilers written in the object oriented method. I think OOP benefits the most in places like LOB, simulations where you can consider everything as an object. But is it really useful in all places? Also OOP can lead to inefficient code than procedural code. Not to mention that design patterns sometimes increase the complexity of design.</p>

答:
Lets try to understand why OOP became popular. It is because of the maintainability problem. Any large codebase has to be just as maintainable as small codebase. Since, OOP features decoupling, modularity, reuse, etc., it helps developing maintainable code. Also, nowadays performance issues are often neglected in favor of maintainability because with advanced algorithms and faster hardware, performance issues can be limited to an acceptable level.

However, there are projects for which different programming paradigms are preferred. Primarily because these projects have different goals. For instance, functional reactive programming have come to fashion for event-based and asynchronous systems development.

So, to answer your question, OOP is the most popular programming paradigm in use now. OOP programmers often times, either out of enthusiasm or ignorance, try to apply it to develop solutions that should be developed using other paradigms.


问:
Reverse a queue using an extra queue
You are given 2 queues, Q1 and Q2. Q1 is already filled with n elements. Q2 is empty

You have to reverse all the elements in Q1.

You cannot use any other space apart from Q2.

only operations permitted would be Q.enqueue() and Q.dequeue()

Time complexity - O(nlogn)

i found this question on a less popular website. http://www.questiondiscussion.com/questions/64/questiondiscussionchallenge-reverse-a-queue-using-an-extra-queue
few answers are also there. i am not able to understand the solutions, can anyone help me with is question ?

答:
q1 has n elements

do

for n-1 elements in q1
take the first element out of q1 (dequeue) and add it to the end (enqueue) q1.Enqueue(q1.Dequeue)

when n-1 elements have been processed (the last element in q1 is next out)

q2.Enqueue(q1.Dequeue) - move it to q2

loop until q1 is empty

In vb it looks like this

```<code>    Dim q1 As New Queue(Of Integer)
    Dim q2 As New Queue(Of Integer)

    'add some elements
    For x As Integer = 1 To 5
        q1.Enqueue(x)
    Next

    Do While q1.Count > 0 'while q1 has elements
        For x As Integer = 1 To q1.Count - 1 'move last to first
            q1.Enqueue(q1.Dequeue)
        Next
        q2.Enqueue(q1.Dequeue) 'move it to q2
    Loop
</code>```

Title: Reverse a queue using an extra queue

Body:
q1 has n elements

do

for n-1 elements in q1
take the first element out of q1 (dequeue) and add it to the end (enqueue) q1.Enqueue(q1.Dequeue)

when n-1 elements have been processed (the last element in q1 is next out)

q2.Enqueue(q1.Dequeue) - move it to q2

loop until q1 is empty

In vb it looks like this

    Dim q1 As New Queue(Of Integer)
    Dim q2 As New Queue(Of Integer)

    'add some elements
    For x As Integer = 1 To 5
        q1.Enqueue(x)
    Next

    Do While q1.Count > 0 'while q1 has elements
        For x As Integer = 1 To q1.Count - 1 'move last to first
            q1.Enqueue(q1.Dequeue)
        Next
        q2.Enqueue(q1.Dequeue) 'move it to q2
    Loop


问:
"Immutable" interfaces
I am confused about the notion of immutability. Consider the following structure of a simplistic calculator:

Here are the interfaces:

```<code>interface IOperationalInterface {
    int Sum(int a, int b);
}

interface IAuditInterface {
    int SumInvocations();
}
</code>```

IOperationalInterface.Sum should compute the sum of two integers and IAuditInterface.SumInvocations should return the total number of received Sum calls.

Here is a trivial implementation:

```<code>class CalculatorImpl : IOperationalInterface, IAuditInterface {
    private int invocations = 0;

    public int Sum(int a, int b) {
        invocations++;
        return a + b;
    }

    public int SumInvocations() {
        return invocations;
    }
}
</code>```

Is CalculatorImpl immutable? Obviously not, because its state changes with each invocation of the Sum method. Is the Sum operation pure? According to Wikipedia it is not, since it changes the state of a mutable object, and that side-effect is observable through the IAuditInterface. Obviously the SumInvocations operation is also not pure, since it may return different results.

In summary, CalculatorImpl is mutable and all of its methods are impure.

However, from the viewpoint of CalculatorClient, who talks to it only through the IOperationalInterface, it appears to be immutable and the Sum operation appears to be pure in the sense that it could not observe any side effects through that interface.

On the other hand, from the perspective of AuditClient, it is completely different: it is obvious that the object implementing the AuditInterface is mutable and its SumInvocations operation is impure, and this follows directly from the specification of the IAuditInterface.

So, it is possible to partition an interface/specification of a mutable class such that some parts of it will appear mutable and some not. In this case, considering only the Sum operation and leaving out the requirement that the invocations should be counted, we get something that does not have any side-effects.

Now, on implementing the CalculatorClient one can take into account the fact that the object behind the interface appears to be immutable. At least one could not tell the difference.

So my question is: does it make sense to talk about "immutability" of interfaces or is it a bad idea? How else can I communicate the fact that there will be no observable side-effects through that interface? And if it's bad, what could go wrong?

UPDATE

Thanks for your answers/comments! I see now that there is no way to say that the IOperationalInterface is pure; the conditions of purity are much too strong to apply in this case. However the question remains whether there is a weaker notion (maybe "immutability"?) which is applicable.

答:
The implementation is clearly not immutable, so let's talk about the "pureness" of the Sum function.

It can only make sense to talk about the implementation, not the interface.  For instance, what if I created a new implementation of the interface with this Sum implementation?

```<code>public int Sum(int a, int b) {
    invocations++;
    if(invocations >= 1000)
    {
        return a + b + 1;
    }
    return a + b;
}
</code>```

The interface hasn't changed, but the method is no longer "pure".

In a purely technical sense, even your naïve implementation isn't pure because eventually invocations will overflow and you'll get an exception when you call Sum instead of the expected result.

Title: "Immutable" interfaces

Body:
The implementation is clearly not immutable, so let's talk about the "pureness" of the Sum function.

It can only make sense to talk about the implementation, not the interface.  For instance, what if I created a new implementation of the interface with this Sum implementation?

public int Sum(int a, int b) {
    invocations++;
    if(invocations >= 1000)
    {
        return a + b + 1;
    }
    return a + b;
}

The interface hasn't changed, but the method is no longer "pure".

In a purely technical sense, even your naïve implementation isn't pure because eventually invocations will overflow and you'll get an exception when you call Sum instead of the expected result.


答:
I believe what you want is a variant of Design by Contract (C# interfaces are a poor man's version of them). In C# it could be achieved via custom attributes and a static analyzer extension (e.g. for Roslyn or ReSharper):

```<code>[Pure] //This is just a sample name, not to be confused with System.Diagnostics.Contracts.PureAttribute
interface IOperationalInterface
{
    int Sum(int a, int b);
}
</code>```

Your custom static analyzer extension would then check if implementation(s) are side-effect free across all the interface methods. This might get complicated depending on the level of guarantee you would like to achieve (e.g. simply checking there are no mutating operators used versus walking any method invocation chains).

If you find this approach viable for your scenario, then consider checking existing contract-related tools for .NET (non of them works well though):

JetBrains: http://www.jetbrains.com/resharper/webhelp/Reference__Code_Annotation_Attributes.html
Microsoft: http://research.microsoft.com/en-us/projects/contracts

Title: "Immutable" interfaces

Body:
I am confused about the notion of immutability. Consider the following structure of a simplistic calculator:

Here are the interfaces:

```<code>interface IOperationalInterface {
    int Sum(int a, int b);
}

interface IAuditInterface {
    int SumInvocations();
}
</code>```

IOperationalInterface.Sum should compute the sum of two integers and IAuditInterface.SumInvocations should return the total number of received Sum calls.

Here is a trivial implementation:

```<code>class CalculatorImpl : IOperationalInterface, IAuditInterface {
    private int invocations = 0;

    public int Sum(int a, int b) {
        invocations++;
        return a + b;
    }

    public int SumInvocations() {
        return invocations;
    }
}
</code>```

Is CalculatorImpl immutable? Obviously not, because its state changes with each invocation of the Sum method. Is the Sum operation pure? According to Wikipedia it is not, since it changes the state of a mutable object, and that side-effect is observable through the IAuditInterface. Obviously the SumInvocations operation is also not pure, since it may return different results.

In summary, CalculatorImpl is mutable and all of its methods are impure.

However, from the viewpoint of CalculatorClient, who talks to it only through the IOperationalInterface, it appears to be immutable and the Sum operation appears to be pure in the sense that it could not observe any side effects through that interface.

On the other hand, from the perspective of AuditClient, it is completely different: it is obvious that the object implementing the AuditInterface is mutable and its SumInvocations operation is impure, and this follows directly from the specification of the IAuditInterface.

So, it is possible to partition an interface/specification of a mutable class such that some parts of it will appear mutable and some not. In this case, considering only the Sum operation and leaving out the requirement that the invocations should be counted, we get something that does not have any side-effects.

Now, on implementing the CalculatorClient one can take into account the fact that the object behind the interface appears to be immutable. At least one could not tell the difference.

So my question is: does it make sense to talk about "immutability" of interfaces or is it a bad idea? How else can I communicate the fact that there will be no observable side-effects through that interface? And if it's bad, what could go wrong?

UPDATE

Thanks for your answers/comments! I see now that there is no way to say that the IOperationalInterface is pure; the conditions of purity are much too strong to apply in this case. However the question remains whether there is a weaker notion (maybe "immutability"?) which is applicable.

Body:
I believe what you want is a variant of Design by Contract (C# interfaces are a poor man's version of them). In C# it could be achieved via custom attributes and a static analyzer extension (e.g. for Roslyn or ReSharper):

[Pure] //This is just a sample name, not to be confused with System.Diagnostics.Contracts.PureAttribute
interface IOperationalInterface
{
    int Sum(int a, int b);
}

Your custom static analyzer extension would then check if implementation(s) are side-effect free across all the interface methods. This might get complicated depending on the level of guarantee you would like to achieve (e.g. simply checking there are no mutating operators used versus walking any method invocation chains).

If you find this approach viable for your scenario, then consider checking existing contract-related tools for .NET (non of them works well though):

JetBrains: http://www.jetbrains.com/resharper/webhelp/Reference__Code_Annotation_Attributes.html
Microsoft: http://research.microsoft.com/en-us/projects/contracts


答:
You're sort of getting hung up on definitions without worrying about why you care if a function is pure or not.  A pure function gives more freedom to the caller at the expense of restrictions on the implementer.  A function with side effects gives more freedom to the implementer at the expense of restrictions on the caller.

Most everyone is familiar with the restrictions on the implementer of a pure function, but many are not familiar with the freedoms it grants the caller.  It frees the caller to cache results and not call the function a second time.  It frees the caller to create as many copies of the object as they want, perhaps on different threads or even different systems, to speed up a computation.  It frees the caller to not have to worry about keeping the object in scope, because they can always recreate an identical one later.

If you're not going to grant those types of freedoms to the caller, it does no good to label an interface immutable.  You're putting restrictions on the implementer without any commensurate benefits to the caller, so you may as well lift the implementer restrictions.

Title: "Immutable" interfaces


答:
However, from the viewpoint of CalculatorClient, who talks to it only through the IOperationalInterface, it appears to be immutable and the Sum operation appears to be pure in the sense that it could not observe any side effects through that interface.

Whatever you can observe through the interface is irrelevant to the concept of purity. If Sum logged results to a file, it would still be impure even though you wouldn't be able to observe any changes through the interface.

Purity is a very strong condition. If you say that something is pure, I'll take you at your word and assume nothing bad will happen if I run it from multiple threads, cache the results and only call it once for any given set of inputs, or that I can call it 1,000,000 times without exhausting the OS's file handles. Those assumptions can backfire when using CalculatorImpl.

There's nothing wrong with partitioning the interfaces the way you have, but you should be precise. The specification you want for IOperationalInterface is probably closer to: "The return value of these methods must depend only on their arguments, but their execution may have side effects." You can be more specific about the side effects and say that the methods must not perform any kind of I/O. But I wouldn't say that it's pure, because you're very clearly not using it that way.

Title: "Immutable" interfaces


问:
When copy/pasting private methods is it necessary to carry along the Javadoc?
So, unfortunately, I'm stuck with code where I'm doing this:

```<code>@Override
method A{
    //calls private methods 1-8
}

private method 1{
    //copy/pasted
}
</code>```

And so on for all of the private methods. I'd have preferred if the developers of the method I'm overriding had made the private methods protected, but I can't change that now.

All of these private methods have javadoc along with them - should I carry this along with the copy/pasted functions in my class and adjust them accordingly, or not waste my time since it is documented in the original file?

答:
I would recommend copying the javadoc along with the methods, since anyone looking at this class in the future may very well have no idea that these private methods are really the exact same as those in the originating class.

Also, when the javadoc for the new class is generated, those methods will not have their intended documentation.  Plus, what if the implementation in either the original or the copied methods changes independently?  It would be very easy for the javadoc to become out of sync.

Finally, since you are simply copying the methods wholesale, it's not really a waste of time to copy the adjacent documentation at the same time.


问:
Architecture for application-wide diagnostic-gathering tool?
My product owner wants us to report more information on the state of the product when a user contacts customer service through an in-app form.  The form eventually results in an email being sent to a customer service email list and handled elsewhere.

The part I'm struggling with is how to augment my existing iOS project to allow for some controller to collect diagnostic information from a variety of disparate classes, and do it in a way that's minimally invasive and won't cause a headache if refactoring later.

Blocks

I've experimented with a few ideas, including having an interface that allows an arbitrary class to register a block to be executed when attempting to collect the diagnostic information:

```<code>[DiagnosticCollectionController addBlockForDiagnosis:^(DiagnosticCollectionController *controller){
    // Add some information here to the controller to send in the diagnostic report
}];
</code>```

Notifications

Another idea I had in mind was to have the diagnostic controller broadcast a notification when it's ready to start gathering information, so that other objects can attach what they need to.  The (potential) advantage here is that I can get away from using blocks thus prevent myself from having block copy issues:

```<code>[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(someSelectorToHandleDiagnosticPopulation:)
                                             name:DiagnosticCollectionControllerWillSendDiagnostics
                                           object:someDiagnosticController];
// Elsewhere
- (void) someSelectorToHandleDiagnosticPopulation:(NSNotification *)note {
    DiagnosticController *controller = [note object];
    [controller addDiagnosticData:someDataDictionary];
}
</code>```

答:
Finally, I went with a setup close to what Randall suggested, after some more thinking and some distraction.

The interfaces that handle coordinating the diagnostic work look like this:

```<code>@interface DiagnosticController
+ (void) addDiagnosticProvider:(id<DiagnosticProvider>)provider;
+ (void) removeDiagnosticProvider:(id<DiagnosticProvider>)provider;
@end

@protocol DiagnosticProvider <NSObject>
- (NSDictionary *) diagnosticData;
@end
</code>```

The DiagnosticController itself keeps a list of __unsafe_unretained pointers so objects can remove themselves from the list of providers when they dealloc.  I went with __unsafe_unretained to make this backward compatible with earlier versions of iOS instead of, say, NSHashTable with the NSHashTableWeakMemory option.  If I have some time in the future, I might cluster the DiagnosticController to allow for multiple backing stores depending on the runtime.

Body:
Finally, I went with a setup close to what Randall suggested, after some more thinking and some distraction.

The interfaces that handle coordinating the diagnostic work look like this:

@interface DiagnosticController
+ (void) addDiagnosticProvider:(id<DiagnosticProvider>)provider;
+ (void) removeDiagnosticProvider:(id<DiagnosticProvider>)provider;
@end

@protocol DiagnosticProvider <NSObject>
- (NSDictionary *) diagnosticData;
@end

The DiagnosticController itself keeps a list of __unsafe_unretained pointers so objects can remove themselves from the list of providers when they dealloc.  I went with __unsafe_unretained to make this backward compatible with earlier versions of iOS instead of, say, NSHashTable with the NSHashTableWeakMemory option.  If I have some time in the future, I might cluster the DiagnosticController to allow for multiple backing stores depending on the runtime.


问:
Effective Repository in C# - Where to put methods?
I'm trying to build a new application using the Repository pattern for the first time and I'm a little confused about using a Repository. Suppose I have the following classes:

```<code>public class Ticket
{

}
public class User
{
   public List<Ticket>AssignedTickets { get; set; }
}
public class Group
{
   public List<User> GroupMembers { get;set; }
   public List<Ticket> GroupAssignedTickets { get;set; }
}
</code>```

I need methods that can populate these collections by fetching data from the database.

I'm confused as to which associated Repository class I should put those methods in. Should I design my repositories so that everything returning type T goes in the repository for type T as such?

```<code>public class TicketRepository
{
   public List<Ticket> GetTicketsForGroup(Group g) { }
   public List<Ticket> GetTicketsForUser(User u) { }
}
public class UserRepository
{
  public List<User> GetMembersForGroup(Group g) { }
}
</code>```

The obvious drawback I see here is that I need to start instantiating a lot of repositories. What if my User also has assigned Widgets, Fidgets, and Lidgets? When I populate a User, I need to instantiate a WidgetRepository, a FidgetRepository, and a LidgetRepository all to populate a single user.

Alternatively, do I construct my repository so that everything requesting based on type T is lumped into the repository for type T as listed below?

```<code>public class GroupRepository
{
    public List<Ticket> GetTickets(Group g) { }
    public List<User> GetMembers(Group g) { }
}
public class UserRepository
{
   public List<Ticket> GetTickets(User u) { }
}
</code>```

The advantage I see here is that if I now need my user to have a collection of Widgets, Fidgets, and Lidgets, I just add the necessary methods to the UserRepository pattern and don't need to instantiate a WidgetRepository, FidgetRepository, and LigetRepository class every time I want to create a user, but now I've scattered the concerns for a user across several different repositories.

I'm really not sure which way is right, if any. Any suggestions?

答:
The second option seems like you are defining your repository based on your requirements for this given application vs 1 repository per "table" which could be more flexible for other areas of your app that might come up or other applications that might not group stuff like your current app does. Yes, it means you'll have a fair amount of repositories, but then they are reusable inside any project that needs access to said repository.

I generally make repositories per "table" (I work in DB mostly) and then make "service" classes (some say UnitofWork I think) that group repositories and has an interface to give functionality to that service.


问:
When is an API considered to be an embedded DSL?
What is the difference between an API and an embedded Domain Specific Language (DSL)?

Is it just syntax?

Consider an API like OpenGL.  How is that different from a graphics DSL?

In other words, if an API is sufficiently complex, can it be considered an embedded DSL?

答:
In general, no. A DSL is deliberately made non-general for the purpose of making some operations more convenient. Things like HTML or Logo were originally domain-specific languages.

In general, you can't embed a DSL into another language even with the most powerful API; whatever you program against that API will still look like a series of expressions in the host language and be not as convenient as using a special-purpose language would be.

The exceptions are languages that provide exceptional opportunities to warp the syntax via a library (operator overloading like C++, inventing new operators like Scala, or even predeclaring a completely different read syntax like Perl with source filters). When you use such a language and take full advantage of the flexibility they offer, then the result can look rather like a new, special-purpose language (but the semantics will often be subtly different from what you would expect if the language were really invented from the ground up to serve your ends).


问:
Does lots of Instance Variables within my class suggest flawed Design?
Ok so I am setting out to consolidate some learning I have been doing. What I am going to do is create a small game relating to a game I enjoy called Persona.

For reference a persona you can think of as a pokemon.

Basically I want the flow to be user chooses a character, a weapon, and a persona (from a list of predefined personas and people i.e. predefined stats and spells for the persona and predefined weapons, stats and personas for the characters). They will choose and I will use maths/ifs/whiles etc to calculate winners.

I currently have a Characters class (with Persona, Stats and Weapon instance variables), a Character Stats class (health, mana etc IVs), a Persona class(with persona stats and name iv), a Persona stats class (agility strength etc IVs) (later I will make the PersonaSpells class) and a Weapons class (attack, hit etc IVs), as well as a Duel class (where all the calculations will be run and methods for player select, enemy selection etc. Additionally with my current implementation all character objects, persona objects and weapon objects etc will be defined in this class and assigned using for example using Character char = new Character(Name, Health, Persona, Weapon, ...), with constructors for persona and weapon defined before this. Finally a main class where I will effectively use an object of the duel class to run the game, and keep the main class and method clearer.

My question is, is this design flawed in that, I end up having to declare loads of objects (as IVs) from constructors of my classes. (So I have an object of all 20 weapons, all 10 characters, all 20 Personas, all 10 character stats, all 20 persona stats) All within my Duel class. Code example below:

```<code>private Weapon deusXiphos = new Weapon();
(x 20 more like this)

private PersonaStats artemisiaStats = new PersonaStats();
(x 20 more like this)

private Persona artemisia = new Persona();
(* 20 more like this)

private CharacterStats mitsuruStats = new CharacterStats(400, 250);
(* 10 more like this)

private Character mitsuru = new Character("Mitsuru", artemisia, deusXiphos, mitsuruStats);
(* 10 more like this)
</code>```

答:
Yes, having many instance variables is a sign that you have a flawed design.

Personally, I put the line around 3 variables if they're mutable and 5 if they're not (if the class is anything more than plain old data). This is uncommonly low. But no matter where the line is, there is a line and having 80 instance variables in a class is going to be over pretty much everyone's line.

Why?

It likely means you've violated the Single Responsibility Principle. When your class has many instance variables, it's unlikely that they provide a cohesive single responsibility for that class. When that fails, it becomes difficult to change the class for one reason without breaking others. It makes it hard to test the functionality of the class in isolation since you need all of its stuff to be there.

It likely means you've violated the Don't Repeat Yourself guideline. What happens when you want to change a field on those stats? Now you have to go to the 30 copies of them and change them all. This increases the chance that you make a mistake and miss one.

It makes it hard to use the Dependency Inversion Principle, because it will be super annoying to pass in 80 objects into your constructor.

Bundling the variables into classes seems like the best approach. Why does the Duel need Mitsuru and Mitsuru's stats? Shouldn't Mitsuru have her own stats?

(though by the letter of the law, that would then lead to a violation of the Law of Demeter when Duel calls mitsuru.Stats.Strength. I don't think that's a particularly egregious error, since it's unlikely that this coupling would cause future errors, and it's far better than the alternative)


答:
Could you, instead of copy pasting, just patch the code across as part of your build? If you marked up the start and end of the copied section in a particular comment style and then had a script pull that into your other file ahead of compilation you would have the same outcome but with an automated process.

That is obviously a terrible solution in general, but compared with copy pasting you are at least not having the same code squirrelled away in multiple places, which is almost guaranteed to cause you problems in future.

Also think very hard about whether there isn't some way you could avoid this altogether by thinking laterally about it. It may not be possible, but sometimes a smart solution will present itself.

Title: When copy/pasting private methods is it necessary to carry along the Javadoc?

Body:
So, unfortunately, I'm stuck with code where I'm doing this:

```<code>@Override
method A{
    //calls private methods 1-8
}

private method 1{
    //copy/pasted
}
</code>```

And so on for all of the private methods. I'd have preferred if the developers of the method I'm overriding had made the private methods protected, but I can't change that now.

All of these private methods have javadoc along with them - should I carry this along with the copy/pasted functions in my class and adjust them accordingly, or not waste my time since it is documented in the original file?


问:
I don't understand the arguments against operator overloading
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.

答:
One difference between overloading a * b and calling multiply(a,b) is that the latter can easily be grepped for. If the multiply function isn't overloaded for different types then you can find out exactly what the function is going to do, without having to track through the types of a and b.

Linus Torvalds has an interesting argument about operator overloading.  In something like linux kernel development, where most of the changes are sent via patches over email, it's important that the maintainers can understand what a patch will do with only a few lines of context around each change. If functions and operators are not overloaded then the patch can more easily be read in a context independent way, as you don't have to go through the changed file working out what all of the types are and check for overloaded operators.


答:
APIs and DSLs are quite different concepts and there are only some areas where they might be said to overlap.

All DSLs are computer languages.  They might be interpreted, compiled, mark-up, query languages (e.g. SQL) or (like JSON or some uses of XML) data languages which might used in messages passed over an API, but they must be languages.  The term describes the nature, not the purpose.

APIs are interfaces allowing one software component to be used by other components.  The term describes the purpose, not the nature.  An API can be a set of object methods, for instance - that is not a DSL.  A web API might use a DSL (or, if it is restful, you might argue that it is a DSL) but a shared, domain specific language is not part of the definition.  A software driver for a device might be written in C, the API distributed as a compiled library, the protocol entirely binary and any language which can use the library might be used to make a client.  Nothing in that API could be called a DSL (a list of symbolic names for the API functions does not cut it).

I'm a little confused as to why you can only see similarities, given the definitions.

Title: When is an API considered to be an embedded DSL?

Body:
What is the difference between an API and an embedded Domain Specific Language (DSL)?

Is it just syntax?

Consider an API like OpenGL.  How is that different from a graphics DSL?

In other words, if an API is sufficiently complex, can it be considered an embedded DSL?


问:
How to maintain view-related information in MVVM and may I store this in the model?
I have an ongoing discussion with some colleagues on how to manage the views to our model.

We've got a model which may be represented by many views. Let's say we've got some data that is stored in an array and we'd like to display the data in a table and in charts.

A certain chart is unique but you're able to duplicate the chart. This duplicate should display the data in the very same way as the original, but it does not display the same part (e.g. if the data is too big to display it at once and you can scroll, so the original shows the first 10 items while the duplicated one shows the last 10).

At any time you can remove a view. The view and the view-model are then deleted from the memory. The model persists even if there's no view representing the data.

There is a handful of displaying information on the view which tells how and what part of the data is displayed. Scrolling is one of those, so let's stay with that example. This displaying information is neither persistent nor is it stored in the model.

If you shut down the application and restart, we don't care about how the view has been before and we always set up a default. If you, however, delete a view and then undo, we'd like to display the data exactly as it's been before deleting. The newly created view is technically not the same as before.

In order to adjust the view, I need to maintain the scrolling position.

I would simply put the displaying information into the model as this continued to exist for the whole time. However, some colleagues disagree and they say the model should only contain persistent data (like the actual data we're representing).

Hence we shouldn't keep track of the displaying information about the view in the model.

Q1: Is it correct from a design perspective that the model contains only persistent data? If yes, how would you maintain view-related information?

As said above, the model may be represented by many views, some of which may be duplicates of each other.

Let's say I found a way to maintain the data. I would have a collection of X displaying information.

Q2: When creating new views which actually replace the old views (keyword undo), how can I determine which displaying information of the collection should be associated to which view.

I mean even if my view had a unique ID, since we've created new one, we cannot rely on this data.

I can't quite figure out how I could associate these information correctly. The only idea that raises is having a separate view-model for each view and keeping the view-models alive, too. On the other hand, I think that's not what it's supposed to be, is it?

答:
I would have to agree with your colleagues.  You don't want to mix View State information with your Model.

Right now you have 1 model and potentially many ViewModels and Views which are destroyed when closed, right?

It sounds like what you need is 1 model, 1 Parent ViewModel, and potentially many Child ViewModels and Views (which, again, are destroyed when closed).  The key difference here is that the Parent VM doesn't get destroyed when the Child VMs do.

Its responsibilities include persisting View State between View instances, and also ensuring no two Views are showing the same portion of the Model (I believe that was one of your requirements?)

This helps keep your View State information separate from your Model and your "Undo" operations are relatively easy to implement.

Something like

```<code>  V     V     V
  |     |     |
  VM   VM    VM
   \    |    /
    Parent VM
        |
      MODEL
</code>```

Body:
I would have to agree with your colleagues.  You don't want to mix View State information with your Model.

Right now you have 1 model and potentially many ViewModels and Views which are destroyed when closed, right?

It sounds like what you need is 1 model, 1 Parent ViewModel, and potentially many Child ViewModels and Views (which, again, are destroyed when closed).  The key difference here is that the Parent VM doesn't get destroyed when the Child VMs do.

Its responsibilities include persisting View State between View instances, and also ensuring no two Views are showing the same portion of the Model (I believe that was one of your requirements?)

This helps keep your View State information separate from your Model and your "Undo" operations are relatively easy to implement.

Something like

  V     V     V
  |     |     |
  VM   VM    VM
   \    |    /
    Parent VM
        |
      MODEL


问:
Which language introduced the idea of private (hidden) variables?
I know C++ had private variables inside classes, and Java, C#, Javascript, and others picked up on that and ran with it. Aside from variable scope, most languages before that just made everything visible. Certainly in assembly, all of memory is accessible (except as limited by hardware).

But was C++ the first language to support the idea of encapsulation?

答:
If you're talking about encapsulation as used in modern OO languages, the clearest and earliest language specification is found in Simula-67. All the key OO features are there, and the language was widely used within a specific community.

If you're talking about encapsulation as equivalent to scope then the clearest and earliest language specification is Algol 58 (aka IAL). The Algol 60 spec was widely implemented, and contains the concepts of function scope and block scope that are now found in all C-like languages.

Around the same time FORTRAN had variables local to subroutines and shared COMMON but not block scope.

Also around the same time Lisp offered dynamic scope and a kind of closure but not lexical scope or encapsulation as we now understand it.


答:
The distinction is hard to make, and depend of the language used. It is also subjective.

In clojure, you can define APIs which look like a DSL. For exemple, hiccup allows you to generate html:

```<code>(html [:span {:class "foo"} "bar"])
</code>```

This can be considered as a DSL with a lisp syntax. The fact that html could be a macro gives it the same amout of power as if you were writing a html templating lib with s-expressions (see sxml)

In python, the same API may look like:

```<code>html(["span", {"class" : "foo"}, "bar"])
</code>```

html is a function. Its argument will be evaluated first, and then the function call will happen. The fact that the python syntax is more specific, and the python semantics are more strict means that this expression is harder to interpret as a DSL independent of the language.

A classic language representation is a tree like data structure and an eval function called recursively on its nodes. LISP languages makes this tree structure very apparent, so any nested function call is indistinguishable from a built-in language feature. That is why the LISP community speak about DSLs for almost everything.

I believe programming is about providing useful abstractions. I find that looking at everything you build (a lib or even the UI of your application) as language elements helping people to solve a complex problem is an effective way to design most things. With this perspective, I assert that every libraries are DSLs, but some of them are poorly designed :-)

Body:
The distinction is hard to make, and depend of the language used. It is also subjective.

In clojure, you can define APIs which look like a DSL. For exemple, hiccup allows you to generate html:

(html [:span {:class "foo"} "bar"])

This can be considered as a DSL with a lisp syntax. The fact that html could be a macro gives it the same amout of power as if you were writing a html templating lib with s-expressions (see sxml)

In python, the same API may look like:

html(["span", {"class" : "foo"}, "bar"])

html is a function. Its argument will be evaluated first, and then the function call will happen. The fact that the python syntax is more specific, and the python semantics are more strict means that this expression is harder to interpret as a DSL independent of the language.

A classic language representation is a tree like data structure and an eval function called recursively on its nodes. LISP languages makes this tree structure very apparent, so any nested function call is indistinguishable from a built-in language feature. That is why the LISP community speak about DSLs for almost everything.

I believe programming is about providing useful abstractions. I find that looking at everything you build (a lib or even the UI of your application) as language elements helping people to solve a complex problem is an effective way to design most things. With this perspective, I assert that every libraries are DSLs, but some of them are poorly designed :-)


答:
I think every API is an embedded DSL but the converse is not true: not every embedded DSL is an API. Only when the language is used as a means to integrate components it can be called an API.

Why can an API be considered an embedded DSL? First of all, it forms a language: it has primitive elements (types and operations) which can be combined (by the means of the host language) to form abstractions and solve complex problems. For example, the OpenGL API can be used to render 3D-scenes in real-time. The Collections API can be used to create algorithms that operate on sets of objects, etc. Second, it is obviously domain specific; for example, the domain of the Collections API is handling sets of objects, and the domain of the OpenGL API is 3D rendering. Hence an API is a domain specific language.

But not every DSL is an API. For example, some DSLs are not to be implemented by a designated component. All systems define some abstractions, and the abstractions which deal with some specific domain can be considered a DSL, but that does not imply that the implementations of these abstractions should be "swappable", in other words, they do not have to form an API. They could, but that is not always necessary. However, in cases when the implementation is "componentized" (sorry for lack of a better term), the DSL indeed becomes an API.


答:
I fully agree with your colleagues that View state does not belong in the Model. That is what you have the ViewModels for.

To support an undo operation of closing a View, you could either keep the ViewModel of a closed View around until it is old enough that the closing can't be undone, or you can implement the Memento pattern to squirrel away the relevant View state in your undo list.

Title: How to maintain view-related information in MVVM and may I store this in the model?

Body:
I have an ongoing discussion with some colleagues on how to manage the views to our model.

We've got a model which may be represented by many views. Let's say we've got some data that is stored in an array and we'd like to display the data in a table and in charts.

A certain chart is unique but you're able to duplicate the chart. This duplicate should display the data in the very same way as the original, but it does not display the same part (e.g. if the data is too big to display it at once and you can scroll, so the original shows the first 10 items while the duplicated one shows the last 10).

At any time you can remove a view. The view and the view-model are then deleted from the memory. The model persists even if there's no view representing the data.

There is a handful of displaying information on the view which tells how and what part of the data is displayed. Scrolling is one of those, so let's stay with that example. This displaying information is neither persistent nor is it stored in the model.

If you shut down the application and restart, we don't care about how the view has been before and we always set up a default. If you, however, delete a view and then undo, we'd like to display the data exactly as it's been before deleting. The newly created view is technically not the same as before.

In order to adjust the view, I need to maintain the scrolling position.

I would simply put the displaying information into the model as this continued to exist for the whole time. However, some colleagues disagree and they say the model should only contain persistent data (like the actual data we're representing).

Hence we shouldn't keep track of the displaying information about the view in the model.

Q1: Is it correct from a design perspective that the model contains only persistent data? If yes, how would you maintain view-related information?

As said above, the model may be represented by many views, some of which may be duplicates of each other.

Let's say I found a way to maintain the data. I would have a collection of X displaying information.

Q2: When creating new views which actually replace the old views (keyword undo), how can I determine which displaying information of the collection should be associated to which view.

I mean even if my view had a unique ID, since we've created new one, we cannot rely on this data.

I can't quite figure out how I could associate these information correctly. The only idea that raises is having a separate view-model for each view and keeping the view-models alive, too. On the other hand, I think that's not what it's supposed to be, is it?


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答: There are loads of symptoms (burn out, overtime, frustration, silence ...) but ultimately you know this is happening when release dates are starting to slip and you are no longer able to deliver the product as often as you are supposed to.</p>


问:
Permutation tests for large sequences
I would like to perform a permutation test on a particularly large data set, i.e. around 4 million entries. Basically, I need to get some number of random permutations of this data set. Usual way to do this, is a Fisher-Yates shuffle, but it's pretty much limited by period of a PRNG. That is, to a sequence no longer than around 2080.

Is there a solution to randomly permuting much larger sequences?

EDIT:
Here is an interesting related discussion on random shuffle algorithms and how much are they limited by RNG.

答:
Let's analyze the minimal number of bits you need to use in order to get a truly (pseudo) uniform random permutation.

Let the number of bits generated be b. We want to find b such that 2^b = n!, so you are going to need log_2(n!) bits at least in order to generate a uniformly distributed permutation which is ~= 8.1*10^7

Fisher-yates shuffle (assuming 32bits integers) will need to generate 32*n~=32*4,000,000~=1.28*10^8 random bits

While indeed there is some waste, it is not as significant as one might think (*1.5 more bits are needed), and to get a uniformly distributed permutation, you are going to need much more than 2080 random integers generated either way.

Title: Permutation tests for large sequences


答: If your view is complex and need to store some data, perhaps your view has a model, a model that belongs only to your view, of course. IMHO this is a different model from your core business model, complex applications can have multiple, independent, models.</p>


问:
Programming by usage
Iv'e been programming for 15 years now and I often read online that it seems like a lot of people will plan out their objects and how they interact and the data they need and that seems to shape the exposed interface. However, I find my brain works from usage backwards to the structure and data. I'm wondering if this is common and any pros/cons to this approach that anyone can think of, and what your mindset is when a new task is thrown your way. I want explore other ideas and approaches in mindset but I only know my mindset and I've been doing it so long. Is this what everyone does?

For example if I were to be tasked with making a stapler class I would write the usage that would make sense to me first and how I would want to use it and then fill in that usage. The first thing I do is open up notepad++ and type:

```<code>Stapler stapler = new Stapler(200);

stapler.Load(200);
stapler.Staple(papers);
stapler.UnJam();
int stapleCount = stapler.StaplerCount;
</code>```

By looking at this it tells me that my stapler needs these functions/properties and I can infer what the parameters are by looking at them most of the time.

I seem to have an easier time thinking in code usage like this vs thinking about an abstract object and all it's functionality before writing any code. Writing out the usage often makes the abstract object real in my mind and is easier for me to grasp.

答:
Like others have commented, your approach is very TDD-like and pretty common.  Although, not everyone takes to that way of writing code - it’s a matter of personal taste really.  If you are looking for other styles to try then have a go at pair-programming with other developers that have differing styles to you and try them out for yourself.

If you are looking for a totally different approach to development - especially for large complex systems - consider having a look at SOA - usually pronounced “Soh-uhh".  This is an non-functional approach to writing software systems (your style appears to be “functional") and the idea is to make everything anti-fragile - problems are isolated to their own areas of concern and is a bit like TDD for software architecture.

Title: Programming by usage


问:
How to define the motion path of one object on a surface of the other one?
I have an uncommon problem. There are 2 3D objects, which are represented by arrays of vertices and triangles (.stl files). Each of them contains a big enough amount of vertices: 1-10 mln ones. The surfaces of these models are rough, and can contain different spikes or hollows.

The aim is to determine path of one these objects, when it moves with contact on the surface of the other one. Moreover, the algorithm should consider how many degrees of freedom are available. In every case there are only 2 objects and one of them is fixed.

Example, object M1 moves on a surface of object M2, which is fixed. It's necessary to move M1 from point A to B. For M1 it's also available one more degree of freedom - along the axis (let's call it AC) perpendicular to AB. So, the path can be only the curve in the plane (AC, AB). But due to this path, during the motion M1 should always has at least one contact point.

I tried to perform it with collision detection algorithm, but it seems it will be very complicated calculations for ordinary computers. Can anybody advise some algorithms, libraries or concepts how to perform this idea?
P.S. I use C, C++ and Java.

答:
One problem is figuring out how the free object can move (e.g. flips along some axis, or translation movements). The other problem is determining how far the free object can move, where it makes contact again with the fixed object (i.e. the collision detection).

I assume that this collision detection is the bottleneck. You can vastly reduce the number of calculations required if you simplify the shape of your objects (i.e. reduce the number of vertices). However, the simplified object must be larger than the actual object. When doing collision detection, you start with a copy of the reduced model. When you find a collision, then you add the vertices etc. from the full-detail model to the copy – but only in the region around the collision! You then resume collision detection with the full detail. For the next movement, you restart collision detection with a new copy of the low-detail model.

This dynamic-detail strategy can be cascaded multiple times. If each level has only half the number of vertices compared with the previous level, then reducing the number of vertices from 10 million to less than thousand would require 14 levels of detail. Less vertices means less calculations to do during collision detection, although storing the multiple levels requires more memory.


问:
How to tell node.js which javascript code runs on server vs client?
I am trying to learn the theory of node.js but can't seem to figure out how node.js knows whether to pre process it on the server or send it to browser for execution.</p>

答:
node example.js runs the code server side.

require('./example.js') within the server-side JavaScript file also runs the code server side.

Serving a static file ending with ".js" to a client will make it a client-side JavaScript.


问:
Which Java based web ui framework to use?

Wicket

Click

GWT

Vaadin

As I understand them, these frameworks all enable gui components to be created using java (with all its benefits) without having to do lots of html/javascript.

As well as considering the technical factors, I am also interested to hear if any are gaining popularity fast. Is a particular framework is becoming the leader of the pack, this will also effect the decision.

答:
Consider why you want the leader of the pack

If it's because you want to be able to easily hire someone with detailed knowledge of the framework then that a poor reason because your choice should be simple enough for anyone to pick it up quickly using in-house examples and documentation.

If it's because you want a strong community, then any of the named entries on Mr Raibles site (tip of the hat to @Alison for the link) will suffice. A quick Google against any of the names you've provided will illustrate their popularity.

Overall, you want a framework that fits well with the way that you and your team develop code. It should be quick to learn and easy to maintain. You'll be working with it day in day out so you'll need to trial it against your most common use cases and see if the other developers like it.


问:
How does a CLI-oriented programmer's workflow differ from a GUI-oriented one?
I've heard a lot about the advantages of doing less programming work in GUI apps and using more command-line tools (especially with regard to getting things done more efficiently).  However, since I don't understand how my workflow would be different if I depended more on command-line tools, I can't readily evaluate whether there's enough of a payoff for me personally to invest time and effort learning a new toolset and changing my workflow.

Right now:

I code some side projects in languages like C/C++/D/C#/Java/Python using Visual Studio, Eclipse, etc., and run them by setting up the build settings, and pressing F5 to build/run.

I'm developing a web program at work, so that involves using Django to set up a server, connect to a database, etc... almost all within the SciTE text editor.

For launching regular programs, I use Launchy... still no terminal. :)

For copying files and whatnot, I use a regular find/move in the graphical file manager (Windows Explorer, Nautilus).

Debugging: I use either Visual Studio or Debugging tools for Windows (if I'm on Windows). I haven't done much debugging on Linux, but for the things I've done, I've used Eclipse (also for Java on Windows).

At work: To connect to the build system and set up a project, I just use tools that have been integrated into Eclipse for my use -- no need for a terminal or anything (although I'm certainly welcome to use a terminal if I indeed want to)

What is it like to do these things in CLI?  Which parts become more/less efficient?  Which aspects of my workflow would need to be changed to get the greatest advantage from a shift to working mostly in CLI?  In other words... If you magically transformed me into a command-line guru, how would my new coding workflow be different from my current, GUI-centered, way of doing things?

答:
Most of my childhood was not spent on a computer since we did even have internet out on the farm. I started programing late in high school and basically worked in GUIs all the time. In college I met a guy who grew up on CLI and did everything that way. So I decided to setup a linux server rather than listen to the prof. After a few years my buddy was watching me write some embedded code and could not believe how I wrote.

I basically use half CLI half GUI. There are some things that GUI bundled environments do much much faster and more efficiently. And the same is true for the CLI. Most of my text editing is done in VIM as the advanced CLI editors VIM/EMACS (no wars here please) make text manipulation the most efficient. Things like Embedded debugging using GDB on the other hand,  is as painful as editing text without a keyboard. Sure its powerful and sure with enough time you will find the information your looking for but having a nice GUI window with instant access to any memory block is invaluable especially when trying to compare it to another memory block.

Anyways what I am really trying to say is that it should not be GUI vs CLI but rather what is CLI better at and what is GUI better at. Because in the end if your IO is slower than your thought process there is a problem.


问:
Should the commit history be used to convey critical information to developers?
During a meeting regarding the rollback of a third-party SDK from the latest version it was noted that the our developers already flagged in the commit history that the latest version should not be used.

Some developers argued that this was a bad practice and it should have instead been noted either in the source file (i.e. // Don't upgrade SDK Version x.y.z, see ticket 1234) or in a project level README file. Others argued that since the commit history is part of the project documentation it is an acceptable location for such information since we should all be reading it anyway.

Should the commit history be used to convey critical information to other developers or should such information be duplicated to another location such as a project README or comments in the relevant source file?

答:
I interpret this situation as having two basic problems, possibly three.

An unwanted SDK upgrade made it into the source, where it could negatively affect the product.

From the question: the contributor who performed the unwanted upgrade didn't know about a previous, specific decision not to upgrade.

The first of these, in my opinion, is the most serious.  If an unwanted SDK upgrade can make it into the code, so can other problems.

Someone suggested adding a unit test case that will fail if it detects the upgrade.  While it would prevent the upgrade from occurring, I believe this is a dangerous path, leading to lava flow over time.  It seems inevitable that at some point in the future the SDK will be upgraded, to bring in new features or bugfixes, or because the old version is no longer supported.  Imagine the head-scratching, maybe even arguments, that will occur when such a unit test then fails.

I think the most general solution is to adjust the development process.  For git, use the pull request process.  For Subversion and older tools, use branches and diff.  But have some process that allows the senior developers to catch these kinds of issues before they make it into the codebase and affect other developers.

If the pull request process had been used in your situation, and if each pull request is narrow and specific, not much time would have been wasted.  A pull request to upgrade the SDK would have been submitted, and declined with comment that the upgrade is not wanted.  No one else would have been impacted, and there would be no need now to revert the SDK upgrade.

But to directly answer the original question, I agree with others that expecting all developers to fully read the entire revision history of the code, release notes, etc. for notices like this is a waste of valuable time.  What's wrong with a short team e-mail?

Possible third issue: Why is the upgrade not wanted in the first place? Clearly at least one developer thought the upgrade would be a good thing. There are many good reasons to delay an upgrade, but also many bad ones.  Take care to avoid the lava flow (unnecessary backwards-compatibility code) and cargo cult ("we can't upgrade that, but I don't know why") anti-patterns!


答:
I wanted to give Matthew's comment more attention by highlighting his important idea in an answer.  There's a reason why you don't want to upgrade your SDK, and that reason should be captured in a unit test.  Not a check for a revision number, but the actual underlying reason.

For example, say there's a bug in the new version.  Write a unit test that checks for that bug.  If they later fix that bug in the SDK, then the upgrade will occur smoothly.  If there's an incompatible API change, write a test that checks that either your code supports the new API or the SDK supports the old API.  That's more of an integration test than a unit test, but should still be doable.

My company generates 50+ commits per day, and we're not exactly huge.  Even if every developer read every single commit message, which let's be frank they don't, the whole reason we need a recorded commit history is because people can't remember it.  And people don't go back and read the history later unless there's a problem.  And they have no reason to suspect a problem on an upgrade that as far as they know hasn't occurred yet.

By all means send an email to prevent duplication of work in the near term, and note it in your build scripts and a README or errata.  However, especially if the problem with the new version is subtle and time consuming to troubleshoot, you need a way of making it obvious.  That means a unit test.

Title: Should the commit history be used to convey critical information to developers?

Body:
During a meeting regarding the rollback of a third-party SDK from the latest version it was noted that the our developers already flagged in the commit history that the latest version should not be used.

Some developers argued that this was a bad practice and it should have instead been noted either in the source file (i.e. // Don't upgrade SDK Version x.y.z, see ticket 1234) or in a project level README file. Others argued that since the commit history is part of the project documentation it is an acceptable location for such information since we should all be reading it anyway.

Should the commit history be used to convey critical information to other developers or should such information be duplicated to another location such as a project README or comments in the relevant source file?


问:
Structuring an application that reads from a .properties file
I have a Java app with three classes: Foo, Bar and Baz. All three depend on a bunch of what are currently constants defined in each class in order to determine how to run. On top of that, Baz interacts with a number of builder classes that need to be set up in various ways.

I'd like to refactor out all of the configuration info in to a .properties file so that I don't have to recompile every time I change a constant.

But I'm not sure how to structure it:

Do I have a ConfigInfoSingleton that holds all of the parameters of the application in static properties, and have other classes ask it for information when they need it? That seems wrong, as it introduces global state.

Do I pass around a ConfigInfoMap as a parameter to all of the classes that need that info? Then I need to have Foo, Bar, and Baz parsing strings in order to decide what they're going to do, and that seems very wrong. Especially in the case of Baz, where I can't just pass around values, but I need to use switch statements on configuration info to determine builder method calls.

Do I parse the info in a different class, and have that class tell the others how to set themselves up? Then I have a class that needs to know about everyone else's implementation details, which seems wrong, but less so than the other options.

This seems like a really basic question but I'm not sure how to proceed in terms of good software design, and I haven't had much luck Googling. Whats the "right" thing to do?

答: Parse the config file and create an object representing the config file's values. Then you can decide how to construct Foo, Bar, and Baz based on the the values of the object's fields.


答:
Here are more observations from a programmer who has lived in both worlds. I won't repeat points already made in other answers:

CLI-based development tends to use a variety of programs, each of which performs 1 function. GUI-based development tends to use 1 big program (the IDE), which performs dozens of different functions. This one difference has several consequences:

Because an IDE is intended to be your one "home" where you work all the time, they may use a proprietary (perhaps binary) format to hold your data. Compatibility isn't a big concern, because they don't expect you to work in 2 different IDEs on the same project. CLI tools, on the other hand, generally just work with plain text files.

With CLI-based development, you can incrementally switch out tools, or integrate new tools into your workflow, more easily. Choosing an IDE is more all-or-nothing, and switching your IDE is more painful.

Using a CLI build script, rather than an IDE's built-in "Build" menu, makes it more likely that you can walk away from your code for a few years, come back to it, and build it without fuss. With GUI-based development, it's likely that you are running a completely different IDE by then. Perhaps the one you were using when you wrote the code doesn't even run on your current OS.

In an IDE, building your own tools means learning a (probably large) plug-in API, and perhaps using a specific language. When using the CLI, nothing special is needed to make custom tools.

On the other hand, the advantage of an IDE is that it is, well, "integrated". So you can click in your editor window to set debugger breakpoints, and so on.

Another point: your choice will also depend on the development platform, OS, and language(s) which you use. On certain platforms, IDE-based development is deeply ingrained in the prevailing development culture. In others, CLI-based development is prevalent. If you are using a platform where IDE-based development is prevalent, it is likely that CLI tools will be poorly developed and poorly supported. The converse is also true.

Title: How does a CLI-oriented programmer's workflow differ from a GUI-oriented one?

Body:
I've heard a lot about the advantages of doing less programming work in GUI apps and using more command-line tools (especially with regard to getting things done more efficiently).  However, since I don't understand how my workflow would be different if I depended more on command-line tools, I can't readily evaluate whether there's enough of a payoff for me personally to invest time and effort learning a new toolset and changing my workflow.

Right now:

I code some side projects in languages like C/C++/D/C#/Java/Python using Visual Studio, Eclipse, etc., and run them by setting up the build settings, and pressing F5 to build/run.

I'm developing a web program at work, so that involves using Django to set up a server, connect to a database, etc... almost all within the SciTE text editor.

For launching regular programs, I use Launchy... still no terminal. :)

For copying files and whatnot, I use a regular find/move in the graphical file manager (Windows Explorer, Nautilus).

Debugging: I use either Visual Studio or Debugging tools for Windows (if I'm on Windows). I haven't done much debugging on Linux, but for the things I've done, I've used Eclipse (also for Java on Windows).

At work: To connect to the build system and set up a project, I just use tools that have been integrated into Eclipse for my use -- no need for a terminal or anything (although I'm certainly welcome to use a terminal if I indeed want to)

What is it like to do these things in CLI?  Which parts become more/less efficient?  Which aspects of my workflow would need to be changed to get the greatest advantage from a shift to working mostly in CLI?  In other words... If you magically transformed me into a command-line guru, how would my new coding workflow be different from my current, GUI-centered, way of doing things?


问:
What time should be recorded against story points in order to determine velocity and hours per point
We recently tried to correlate the hours spent on a sprint against the stories assigned to the project (to try and get an idea of velocity and hours per point).  However our recording system only allowed us to put time against a project and so included time such as:

Customer meetings / phone calls

Scrums

Development / testing

Should all of the time for these be taken into account when trying to determine velocity.  Or should only the development / testing time be taken into account that occurred against specific stories.

If everything, what should scrums and meetings be against.  Should there be a separate story for these, or just recorded against a different metric i.e. project-elaboration vs project-development.

If only development do we need a finer grained recording system for recording time spent on a project?

EDIT:  As well as velocity we are also trying to get a better idea of hours per point

EDIT:  I've had a few comments saying this isn't the way to do it  (that's great).  However no-one in those comments has suggested how we can give a priced quote for the next lot of work if we won't know how long the points took on an hour basis.  The customer wants to know how much cost the next lot of work will be.

Some additional points to note are:
1. The team isn't solely dedicated to this project.  Some time is spent on other work for some people and this may vary.
2. The team may vary in size as the project goes with a member coming and going (I guess this effects estimations, but how?)

答:
If you have sprints of consistent length (which is highly recommended), then your Velocity is simply the number of story points of the stories that were completed that sprint.

For example, if your team committed to stories for a total of 21 story points and at the end of the sprint you delivered 19 story points worth of completed stories, then your velocity for that sprint is 19 story points.

Note that stories that aren't completed don't count towards your velocity, regardless of how much effort went into them and even if they are 95% done. Only 100% done counts.

If your sprints are not of a consistent length (or if you need to compensate for holidays), then you could work with an average velocity per day. You simply calculate that by dividing the sprint velocity by the length of the sprint (in working days).

If the sprint in the example was 3 weeks (15 days), then you would have an average velocity of 1.19 story point per day.

If you use story points also to make a quote and you want to track how much effort goes into a story point, it is best to count only the technical work and add a fixed percentage for overhead (meetings and similar non-technical billable work).

This calculation should be independent from your velocity calculation and can include effort spent on stories that aren't fully done at the end of the sprint.


答:
As Doval mentions you could parse your *.properties file and create a class that represents your properties and then pass it along to your classes.

A different approach is also to look into a framework that can handle this for you. Spring does not only inject your dependencies but also handles properties very well. This questions gives a good example on how to use Spring together with *.properties files.

There is also less intrusive libraries available such as Owner that supports live reloading of your properties amongst other things.

Title: Structuring an application that reads from a .properties file

Body:
I have a Java app with three classes: Foo, Bar and Baz. All three depend on a bunch of what are currently constants defined in each class in order to determine how to run. On top of that, Baz interacts with a number of builder classes that need to be set up in various ways.

I'd like to refactor out all of the configuration info in to a .properties file so that I don't have to recompile every time I change a constant.

But I'm not sure how to structure it:

Do I have a ConfigInfoSingleton that holds all of the parameters of the application in static properties, and have other classes ask it for information when they need it? That seems wrong, as it introduces global state.

Do I pass around a ConfigInfoMap as a parameter to all of the classes that need that info? Then I need to have Foo, Bar, and Baz parsing strings in order to decide what they're going to do, and that seems very wrong. Especially in the case of Baz, where I can't just pass around values, but I need to use switch statements on configuration info to determine builder method calls.

Do I parse the info in a different class, and have that class tell the others how to set themselves up? Then I have a class that needs to know about everyone else's implementation details, which seems wrong, but less so than the other options.

This seems like a really basic question but I'm not sure how to proceed in terms of good software design, and I haven't had much luck Googling. Whats the "right" thing to do?


答:
Been there. Done that.

What I did when I had a similar situation was:

Regarding the configuration:

Created a wrapper around a Properties class, I called that wrapper Context

That wrapper reads and parses the property file

I created a ContextDependand interface with a setContext(Context c) method

I have Foo, Bar and Baz implement that interface

I inject that Context object into my Foo, Bar and Baz classes so they can acces it without it being a Singleton

Regarding the creation problem:

I used the Builder pattern

I created a Builder interface with just a build method

Created a FooBuilder, a BarBuilder, a BazBuilder, etc. that implement Builder and return an object which is a superclass of my other classes or an interface they implements

I added each builder to a HashMap with a key, like map.put('FOOBUILDER',new FooBuilder())

Then, instead of a long case structure, I just look up the builder in the HashMap and get it build the object for me, or I traverse the hash and build all of them

That way I tell in the properties files what objects of a collection to build and that can be done without recompiling

If the Builder part is not want you were asking for, at least try the property wrapper / context injection part.