答:
The Unified Modeling Language is not so much unifying programming paradigms. It is dramatically focused towards object-oriented programming (hence, f.ex. its most popular diagram being the class diagram). In contrast, sum types are typically a feature of functional languages (like F#, Haskell, etc.).

I'm afraid to inform you that UML is probably not a good choice to model programs that will be developed with a functional language. A huge bag of their features do not have direct correspondences in UML unfortunately. Features that form the bread-and-butter of FP, like first-class functions, type constructors, etc., are troublesome to represent in UML, or flat out impossible.

If you must represent sum types, then you could model a representation that is close to their implementation in Scala, where you actually define a base class/trait/interface and derive the individual sum types. Something like this (simplified):

```<code>sealed trait Option[+A]
case object None extends Option[Nothing]
case class Some(value : T) extends Option[T]
</code>```

Of course, you will fall short of modelling this in several aspects (trait? case class? covariance? sealed?), but that is my general experience when you try to model non-OOP features in UML.

Title: What do I use for a variant in a UML class diagram?

Body: Does standard UML specify how a variant (aka tagged union, discriminated union, sum type, etc) should be depicted in a class diagram? </p>

Body:
The Unified Modeling Language is not so much unifying programming paradigms. It is dramatically focused towards object-oriented programming (hence, f.ex. its most popular diagram being the class diagram). In contrast, sum types are typically a feature of functional languages (like F#, Haskell, etc.).

I'm afraid to inform you that UML is probably not a good choice to model programs that will be developed with a functional language. A huge bag of their features do not have direct correspondences in UML unfortunately. Features that form the bread-and-butter of FP, like first-class functions, type constructors, etc., are troublesome to represent in UML, or flat out impossible.

If you must represent sum types, then you could model a representation that is close to their implementation in Scala, where you actually define a base class/trait/interface and derive the individual sum types. Something like this (simplified):

sealed trait Option[+A]
case object None extends Option[Nothing]
case class Some(value : T) extends Option[T]

Of course, you will fall short of modelling this in several aspects (trait? case class? covariance? sealed?), but that is my general experience when you try to model non-OOP features in UML.


问:
Java 1.7 library with a Java 1.5 program - what are the options
I have a class library which is compiled with JDK 1.7 It uses several 1.7 features and classes and would be very difficult to get it recompiled in JDK 1.5.

This needs to integrate with an old legacy application with is currently running on JRE 1.5. The integration itself will be quick because the library has just 1 class and very little methods which need to be called from the application. The application owners aren't ready to move to Jre 1.7 immediately.

What are my options here? Is there a way to quickly convert the library into a Server on which the methods can be called remotely by the application? Are there any frameworks available to get this up and running quickly? I don't want to spend too much time on this because the application will move to 1.7 in a years time and this is a stop gap thing for the meantime.

Is there a better way to do this?

答:
I don't get it.

It uses several 1.7 features and classes and would be very difficult to get it recompiled in JDK 1.5.

Okay. To backport a library may be a big (expensive) task. But on the other hand, you say:

The integration itself will be quick because the library has just 1 class and very little methods which need to be called from the application.

So, why not simply port the parts you need and leave the rest out? 1 class and some methods sounds like work for an afternoon.

The application owners aren't ready to move to Jre 1.7 immediately.

But, they are aware, that the current Java Version is 8? And they are also aware of the fact, that the JVM improved a bit since Java 5? Despite the fact, that it isn't your decision, as a responsible programme who cares, you should inform the decision makers.

1.7 in a years time and this is a stop gap thing for the meantime.

Why not port it directly to Java 8?

What are my options here? Is there a way to quickly convert the library into a Server on which the methods can be called remotely by the application? Are there any frameworks available to get this up and running quickly?

Hm. There is an easy solution: http://projects.spring.io/spring-boot/ which does exactly that.

Spring Boot is easy to set up. Define some custom routes, which map to your lib. You write and deploy Spring Boot together with the library on a JDK 1.7 box and call over from the other machine. Done.

ContentLicense: CC BY-SA 3.0


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
I tend to be clever, but I strive to be elegant.

Develop code now that others will not try and avoid later.

ContentLicense: CC BY-SA 2.5


问:
How to work on not User Story related tasks
I'd like to create a developer task collector where I'd put all issues that I see need some work but are not User Story related (e.g. fix some not visible quirks in startup animation, scan code with lint, enable EasyTracker in application, clean unused resources, etc.).

I don't know when we'll have time to work all those issues, maybe next Sprint we'll do one of them and two Sprints later we'll work one etc.

How to deal with it in Scrum/Sprint planning? Also should Product Owner decide what to do and when?

答:
This depends on the nature of your non-user-story-related tasks. Have you considered tracking impediments in your team.

In Scrum, an impediment is anything that keeps a team from being productive.

The tasks you mentioned could (partially) be considered impediments and you can work on a certain amount of impediments in a sprint. As for who decides what to do, in the case of impediments, it is really up to the team. They (should) know, where it hurts the most.


问:
Using entityManager/repository Class/session factory directly in controller
I wonder what is your approach on following subject:

let's say we have MVC structure with entities, repositories, controllers and service layer.

My approach to use above was pretty clear for me:

controller uses services

services perform manipulations to data when
needed,

services use repository classess to save and update data
from db

controller gets services output (when needed) and pushes it
to view

However, yesterday I stumbled upon solution popular in Symfony2 world, in which

controller has access to entityManager/sessionFactory

controller uses services to perform manipulations to data

controller uses entityManager/sessionFactory and repositories directly to perform database reads, saves and handle transactions.

At first I disagreed with second approach, I know it breaks some clean architecture principles, but... it is shown in a lot of official tutorials on Symfony2 website. So I thought it would be better to ask.

In other words:
is it ok to make controller directly responsible for saving and retrieving data as well as handling transactions? What are ups and downs?

答:
There's a risk that the second approach leads to a Fat Controller, which is often considered an antipattern. It's effectively a violation of "clean architecture" (as by Uncle Bob Martin) since your controller is now not only a "delivery mechanism" but also deals with applicative transactions/use cases, orchestrating calls to the repositories and services and making decisions based on current state of the application.

Drawbacks are on readability, bug proneness, maintainability and testability since UI logic is now intertwined with applicative logic. It can also favor code duplication (in contrast, code in a service can be reused by multiple controllers) and if you choose to add another UI layer (say, mobile) to your architecture, the use cases will have to be copied there. Same if you want to add a UI-less HTTP API.

The main advantage is simplicity. With a small CRUD application where each HTTP request results in the same basic steps (load entity, update/delete/display it, [save entity]), you don't necessarily need this layer of indirection. Applicative logic can even be factored out to a base controller class with template methods.


问:
Why do browser Javascript libraries pass the window object as an argument?
While looking at various JavaScript libraries, I have noticed a relatively common practice of passing either the window or the document object as part of the arguments given to the library initialization function.

Examples:

DOM4

ContentLoaded

EasyXDM

fingerprintjs

While I understand very well why that would be done for libraries that are designed to run on non-browser environments, I do not know why that is done for libraries that seem designed only for client browser environments. (Such as all the examples given above).

答: It also helps to speed up the library as window or document is now locally bound. And this also ensures that if latter the user, replaces the window object with say: window = "Help, I'm trapped in a window overwriting assignment statement.";; the library continues to work.


问:
Mark x% items in stream
There are n items  (n is known and > 1,000,000,000).

I want to randomly 'mark' x% of n-items in stream.

(n and x are known)

Items are in stream ,one directional (you can't go back) processed item goes to output stream. Items should be picked randomly as well, meaning I can't take the first %x of items in stream.

complexity should be <= O(n).

My question:

Will it be correct to "test" each item independently?

Meaning, take item from stream -> x% to mark it...
Take next item...

答:
It will be asymptotically correct, i.e. it will provably tend to approach the specification as time goes on. However, for an unspecified amount of time, it will deviate from the specification, possibly quite severely (and possibly much more than it would have to, given that you can't partially mark an item).

Whether that is good enough for your use case is a question that only you can answer. If you do have to approximate the specified percentage as closely as possible, then your suggestions is not good enough, and you'll have to maintain additional counters as well. (However, that shouldn't take you out of the realm of linear-time solutions.)

Title: Mark x% items in stream


答:
If you simply mark x% by probability independent for each item you might not end up for a fixed n with exactly x% of the n items.

I recommend something like this:

n is known, so you can calculate how many items you have to mark markSize=n*x/100.

Now take the first markSize items from the stream and while reading the rest of the stream replace them randomly by the related probability.

The simplified example, if you want to mark one out of a stream of n:

take the first one as mark-candidate

read the second one from the stream and replace your old mark-candidate by it with a probability of 1/2

read the third  one from the stream and replace your old mark-candidate by it with a probability of 1/3

and so on
(In this case you do not even need to know n up front.)

This idea can be generalized for any number of items to mark from a stream. Since you only read the stream once, the time complexity is O(n).

Title: Mark x% items in stream

Body:
There are n items  (n is known and > 1,000,000,000).

I want to randomly 'mark' x% of n-items in stream.

(n and x are known)

Items are in stream ,one directional (you can't go back) processed item goes to output stream. Items should be picked randomly as well, meaning I can't take the first %x of items in stream.

complexity should be <= O(n).

My question:

Will it be correct to "test" each item independently?

Meaning, take item from stream -> x% to mark it...
Take next item...


答: It should work acceptably in your use case. The general rule is that the distribution of the number of marked items across many sample will have mean e (where e is n times x%) and standard deviation sqrt(e). This means you have 99.7% chance that the number of marked items will fall between e-3sqrt(e) and e+3sqrt(e). Let's say n=1,000,000,000 and x=1%. Then e=10,000,000 and sqrt(e) is roughly 3,000. You can have 99.7% certainty that the number of marked items will fall between 9,994,000 and 10,006,000. That's probably good enough for your purposes. As x becomes very small, though, the accuracy decreases.</p>

Title: Mark x% items in stream


答:
Lets say you have n items and know you want to mark m items, m<=n (according to the % value). Now you mark the items one-by-one, starting with a random probability of m/n for marking the first item. But instead of keeping that probability fixed, after each step you adapt the actual probability to what is needed now!

So when after k steps you have marked l items, you will have to process (n-k) remaining items, and you want to have (m-l) of them marked. So choose the probability of the next item as (m-l)/(n-k).

As you see, the more l approaches m, the smaller the probability of marking will become. When l is equal to m, the probability is 0. On the other hand, when the number of remaining items reaches the number of remaining items to marked, the probability will become 1. Finally, you will end up with exactly m marked items.

It should be obvious that the run time is O(n), since each element is processed once, and the only thing you have to keep track is the both numbers (m-l) and (n-k).

Title: Mark x% items in stream


问:
DDD, modularizing the application and domain layers without breaking the DIP
Quoting DDD theory:

The application layer is thin in terms of domain logic - it merely
  coordinates the domain layer objects to perform the actual work.

When it comes to modularization, and assuming that the module containing the domain entities and the interfaces of the domain services belongs to the domain layer, the application layer depends on the domain layer, which breaks the dependency inversion principle.

The implementation of the high-level component's interface by the low
  level component requires that the low-level component package depend
  upon the high-level component for compilation, thus inverting the
  conventional dependency relationship.

What am I missing?

I add an UML diagram to clarify the problem I see.

The Persistence Layer depends upon an abstration in the Domain Layer
-> DIP ok!

The Application Layer depends upon an abstraction in the Domain Layer -> Does this break the DIP?

答:
It doesn't break DIP because Domain is the highest level, higher than Application, and doesn't have a dependency on it. The reverse (Domain depending on Application) would break DIP.

Also, the "should depend on abstraction" part of DIP doesn't necessarily apply here, because domain entities can't be abstracted -- they are already a pure conceptual model of your domain. The only exception may be Domain Services, because you could place an interface in front of those.

As a side note, you generally don't need to leverage dependency inversion inside the Domain model itself, because

Domain entities have few to no collaborators

The ones they have are well identified (ubiquitous language) and often not polymorphic in nature

Domain resides entirely in memory with no external communication (3d party framework, network, disk, etc.) involved, so it can be tested with fast integration tests without needing mocks.

ContentLicense: CC BY-SA 4.0


答:
The DI means your Application layer shall not depend directly on the Domain Service classes, but on abstract interfaces of those service classes (actually, your diagram is already showing this). The only thing which is debatable is if those interfaces should be placed in the Domain Layer. You better place them outside, in a "Service Interface" layer, so they can be referenced from the Application layer as well as from the Domain layer. This way, you have no direct dependendencies between Application layer and Domain layer, in none of the two possible directions.

Of course, as Greg has already pointed out, somewhere in your application you have to wire everything together and actually create non-abstract instances of your Domain Service classes. Either you use a DI framework for this purpose, or you do this manually in a kind of "infrastructure" part of your program, outside of any of the classic "layers". Neither a DI framework, nor a manual start-up infrastructure is relevant in the sense of the DIP.

Title: DDD, modularizing the application and domain layers without breaking the DIP

Body:
Quoting DDD theory:

The application layer is thin in terms of domain logic - it merely
  coordinates the domain layer objects to perform the actual work.

When it comes to modularization, and assuming that the module containing the domain entities and the interfaces of the domain services belongs to the domain layer, the application layer depends on the domain layer, which breaks the dependency inversion principle.

The implementation of the high-level component's interface by the low
  level component requires that the low-level component package depend
  upon the high-level component for compilation, thus inverting the
  conventional dependency relationship.

What am I missing?

I add an UML diagram to clarify the problem I see.

The Persistence Layer depends upon an abstration in the Domain Layer
-> DIP ok!

The Application Layer depends upon an abstraction in the Domain Layer -> Does this break the DIP?


问:
What's so bad about creative coding?
I was watching Bob Ross paint some "happy trees" tonight, and I've figured out what's been stressing me out about my code lately.

The community of folks here and on Stack Overflow seem to reject any whiff of imperfection.  My goal is to write respectable (and therefore maintainable and functioning) code, by improving my skills.  Yet, I code creatively.

Let me explain what I mean by "coding creatively":

My first steps in a project are often to sit down and bash out some code.  For bigger things, I plan a bit out here and there, but mostly I just dive in.

I don't diagram any of my classes, unless I'm working with others who are creating other pieces in the project.  Even then, it certainly isn't the first thing I do.  I don't typically work on huge projects, and I don't find the visual very useful.

The first round of code I write will get rewritten many, many times as I test, simplify, redo, and transform the original hack into something reusable, logical, and efficient.

During this process, I am always cleaning.  I remove unused code, and comment anything that isn't obvious.  I test constantly.

My process seems to go against the grain of what is acceptable in the professional developer community, and I would like to understand why.

I know that most of the griping about bad code is that someone got stuck with a former employee's mess, and it cost a lot of time and money to fix.  That I understand.  What I don't understand is how my process is wrong, given that the end result is similar to what you would get with planning everything from the start.  (Or at least, that's what I have found.)

My anxiety over the issue has been so bad lately that I have stopped coding until I know everything there is about every method for solving the particular problem I am working on.  In other words, I have mostly stopped coding altogether.

I sincerely appreciate your input, no matter what your opinions are on the issue.

Edit:  Thank you all for your answers.  I have learned something from each of them.  You have all been most helpful.

答:
I can definitely recognize myself in the way you describe your workflow. Here's the thing: when I started working in a group environment, almost all that stuff HAD to change.

The job I've been in for about 8 months now is really my first experience at working in a team of developers on a single project. Until now, literally my whole career has been as a lone-wolf coder who didn't have to deal with all that comes with teamwork. Even when I worked in a group, it was always fairly siloed work--I had my project that was MINE, or my section of it that was MINE, etc. It was an interesting learning curve as I brought myself up to speed with a truly collaborative team work environment.

Here's the main thing I've realized: if it's not bloody obvious what you're doing, you're probably writing a colleague's next headache. Most of the "process-oriented" fussiness you see here has to do with the fact that many of us have BEEN the colleague with the headache. And most software process management theory has to do with minimizing that headache.

So things like planning out an agreed-upon plan ahead of time, etc... Those are about having a team on board and in sync. If you're the team, you're already in sync with yourself, and that's not really necessary.

Title: What's so bad about creative coding?


问:
Why are Apache 2.0 works excluded from OpenBSD?
From http://www.openbsd.org/policy.html

The original Apache license was similar to the Berkeley license, but source code published under version 2 of the Apache license is subject to additional restrictions and cannot be included into OpenBSD.

This rationale mentions "additional restrictions" but doesn't say what they are. What were the reasons for declaring the Apache 2.0 license incompatible with OpenBSD policy?

答:
A few criticisms I found on the mailing list:

It's too complex / hard to understand for non lawyers

The copyright notice requirements are annoying

The patent provisions make the license non free

It's worse than the previous license.

From: Henning Brauer (lists-openbsdbsws.de)

  Date: Thu Feb 19 2004 - 02:58:21 CST

the point is that more and more free software is slowly getting unfree,
   more restrictive, etc, and that is not something we should just
   passively watch.
   please have a look at the new apache license.
   it is not really parsable without consulting a lawyer, and as this
   license seems to go into the contract law land, the lawyers answer
   migth very well be a differing depending on in which country you are.

From: Steve (steveszmidt.org)

  Date: Mon Jun 07 2004 - 13:59:03 CDT

Yes indeed. Reading the Apache 2.0 license, it demands notices to be placed in
   any modified versions that you distribute. BAAD!

It even have the gall to demand that if you "prepare Derivative Works", "to
   carry prominent notices stating that You changed the files". Including
   original copyright notices and stuff.

This is truly evil.

Besides being so nasty it's a really easy to read license for any layman.
   Guess they figured that if anyone can read and understand it they will stay
   away from Apache.

To cap it off, unless you explicitly state otherwise, any contribution
   intentionally submitted, will follow the same license! So now others in
   their turn also have to include notices and so on. This is a truly unfriendly
   license...

From: Theo de Raadt (deraadtcvs.openbsd.org)

  Date: Fri Feb 20 2004

No sorry, the Patent clause seems to give extra rights: the right not
    to be sued by a contributor for using their code, so in that sense
    the extra length does seem to make the licence more free.

That's funny; I cannot see any such thing being covered by copyright

  law. As you may know, copyright law only allows you to keep or grant

  away the rights covered by copyright law. And since this is a right

  not discussed in copyright law, good god, it must not be a valid

  copyright term.

There has been a load of knee-jerk nonsense from people who clearly
    can't (or don't want to) read, asserting that this removes users
    rights to sue. It doesn't, it merely removes rights if they sue that
    they would never have had under a BSD licence in the first place.

Balony.

What bothers me is a bunch of OpenBSD folks going over to Apache
    licensing lists making assertions that clauses like the patent clause
    make the license inherently less free based on poor analysis.

It is not free. There is no such thing as a "right to not be sued".


问:
Programming CPU Emulator Functional Style
I want to write an 8086 CPU emulator in javascript, functional style.
How would one conceptualise / design an 8086 emulator, or any CPU emulator that has registers and realmode memory access in a functional way?

I can't wrap my head around how an emulator that is pure / mostly side effect free in the core parts, like memory IO and registers, would work.

I have seen this Code Golf: Emulate an Intel 8086 CPU - In it, someone gave an answer in Haskell, so it seems possible.

答:
You have a couple of stateful properties. Those are the registers and memory. And we have a transition between states. This is each CPU cycle. We can therefore model this architecture in a straightforward fashion:

```<code>function cycle(state: State) -> State { ... }
</code>```

Our cycle function will treat the input state as an immutable object, and create a new state to return. This involves copying most data over to the new state. This is not a problem until you start caring about performance.

The CPU cycles until some halting state is reached. This could be expressed as a loop:

```<code>while(! state.isHaltingState()) {
    state = cycle(state);
}
</code>```

which could of course also be expressed as infinite recursion.

Inside our cycle function, we locate, decode, and perform the current instruction. All instructions will at least mutate the instruction pointer. In JavaScript (which is not a pure functional language), the approach would be:

Make a copy of the old registers

Execute the current instruction, which possible mutates the current registers

Treat the registers as immutable and add them to the next state

Return the next state.

Unlike registers, memory (= an array of memory cells, e.g. bytes) will not necessarily be mutated during each instruction. If memory was not touched, we don't have to perform a copy and can simply reference the old memory in the next state. If we do change any cell, we have to create an updated copy for use in the new state. The impact of this can be reduced by dividing memory into pages, and only replacing pages that were actually touched. Effectively, this approach turns the array into an n-ary tree of arrays of fixed depth.

I would model each instruction as a function that calculates a delta from the current state. This way, the code for applying the delta to the current state and returning a new state in an effective manner does not have to be repeated throughout the code. A delta could be a small object such as { registers: { eax: 0x42}, memory: {0x1234: 0x00} }.

Body:
You have a couple of stateful properties. Those are the registers and memory. And we have a transition between states. This is each CPU cycle. We can therefore model this architecture in a straightforward fashion:

function cycle(state: State) -> State { ... }

Our cycle function will treat the input state as an immutable object, and create a new state to return. This involves copying most data over to the new state. This is not a problem until you start caring about performance.

The CPU cycles until some halting state is reached. This could be expressed as a loop:

while(! state.isHaltingState()) {
    state = cycle(state);
}

which could of course also be expressed as infinite recursion.

Inside our cycle function, we locate, decode, and perform the current instruction. All instructions will at least mutate the instruction pointer. In JavaScript (which is not a pure functional language), the approach would be:

Make a copy of the old registers

Execute the current instruction, which possible mutates the current registers

Treat the registers as immutable and add them to the next state

Return the next state.

Unlike registers, memory (= an array of memory cells, e.g. bytes) will not necessarily be mutated during each instruction. If memory was not touched, we don't have to perform a copy and can simply reference the old memory in the next state. If we do change any cell, we have to create an updated copy for use in the new state. The impact of this can be reduced by dividing memory into pages, and only replacing pages that were actually touched. Effectively, this approach turns the array into an n-ary tree of arrays of fixed depth.

I would model each instruction as a function that calculates a delta from the current state. This way, the code for applying the delta to the current state and returning a new state in an effective manner does not have to be repeated throughout the code. A delta could be a small object such as { registers: { eax: 0x42}, memory: {0x1234: 0x00} }.


问:
Why do functional programs have a correlation between compilation success and correctness?
I've been trending toward functional programming for 4 years now, ever since I first started working with LINQ.  Recently, I wrote some pure functional C# code and I noticed, first hand, what I've been reading about functional programs - that once they compile they tend to be correct.

I tried to put a finger on why this is the case but I have not succeeded.

One guess is that in applying OO principals, you have an "abstraction layer" that isn't present in functional programs and this abstraction layer makes it possible for the contracts between objects to be correct while the implementation is wrong.

Has anyone thought about this and come up with the underlying abstract reason for the correlation between compilation success and program correctness in functional programming?

答:
I don't think there's a significant correlation between functional programming compilation and runtime correctness. There may be some correlation between statically typed compilation and runtime correctness, since at least you may have the right types, if you're not casting.

The programming language aspect that may somehow correlate successful compilation with runtime type correctness, as you describe, is static typing, and even then, only if you're not weakening the type checker with casts that can only be asserted at runtime (in environments with strongly typed values or places, e.g. Java or .Net) or not at all (in environments where the type information is lost or with weak typing, e.g. C and C++).

However, functional programming per se may help in other ways, such as avoiding shared data and mutable state.

Both aspects together may have a significant correlation in correctness, but you must be aware that having no compilation and runtime errors tells nothing, strictly speaking, about correctness in a broader sense, as in the program does what it is supposed to do and fails fast over invalid input or uncontrollable runtime failure. For that, you need business rules, requirements, use cases, assertions, unit tests, integration tests, etc. In the end, at least in my opinion, they provide much more confidence than either functional programming, static typing or both.


问:
IoC, Unity and passing parameters (or a way to avoid doing so)
While the concept of IoC isn't foreign to me, I'm new to Unity and I'm having trouble connecting the metaphorical dots, so to speak.

In our project we have a class library for logic, then several class libraries with repositories implementing common interfaces (they provide access and allow CRUD operations on different data sources). Finally, this is all used together in either an MVC web site or a SharePoint site.

We wanted to implement Unity to keep a single configuration and make the whole thing better.

But... there are some design issues I'm facing. For example - the MVC web site, as far as communicating with the underlying SQL database is concerned, can have everything it needs specified in the configuration section for the Unity container. However, said web site also needs to occasionally connect with SharePoint... in order to create a SharePoint repository, I need to create an SPWeb object and pass it to the repository constructor.

I CAN do that using ParameterOverride when resolving the type, but this doesn't... feel right. There are cases where a larger number of parameters need to overridden this way; to resolve a logic class I need to pass repositories, which in turn are resolved by passing a manually created SPWeb object... When this happens it seems I'm no longer following an IoC pattern. The kicker here is that I cannot have the SPWeb object defined in the Unity container!

Is there a pattern (a practical example would be superb) where Unity is used but certain values are being passed TO the container while resolving types, without the need to use ParameterOverride?

EDIT

I feel I need to provide a more specific example of why ParameterOverride is a problem. Below is a fragment of code used by a SharePoint timer job. The job in question synchronizes some data between SharePoint and SQL, so it requires two different repositories implementing the same interface. Because the code is ran from SharePoint, it cannot access a global configuration defined DataContext (EntityFramework, code-first) because there's no web.config file to read the connection string from. Also, due to the weirdness that is SharePoint, I cannot "get" the current SPWeb object, and instead need to create it on the fly.

The end result is a ton on using statements, and a lot of parameters need to overridden when using Resolve. Also, the need to pass the parameter NAME as a string would make this really difficult to code for anyone else - this information isn't known from the interface alone.

```<code>    public override void Execute(Guid targetInstanceId)
    {
        var siteUrl = Properties["Site"] as string;
        var sqlConnection = Properties["SQL"] as string;
        if (String.IsNullOrEmpty(siteUrl))
            throw new ArgumentNullException("Site URL is missing.");
        if (String.IsNullOrEmpty(sqlConnection))
            throw new ArgumentNullException("SQL connection string is missing.");

        using (var site = new SPSite(siteUrl, SPUserToken.SystemAccount))
        using (var web = site.OpenWeb())
        using (var spPollRepository = Configuration.ServiceLocator.SharePointContainer.Container.Resolve<IPollRepository>(new ParameterOverride("web", web)))
        using (var ctx = Configuration.ServiceLocator.SharePointContainer.Container.Resolve<Repositories.PollsDataContext>(Configuration.ServiceLocator.SqlNamedRegistration, new ParameterOverride("nameOrConnectionString", sqlConnection), new ParameterOverride("initialize", false)))
        using (var sqlPollRepository = Configuration.ServiceLocator.SharePointContainer.Container.Resolve<IPollRepository>(Configuration.ServiceLocator.SqlNamedRegistration, new ParameterOverride("ctx", ctx)))
        {
            IPollsSyncLogic logic = Configuration.ServiceLocator.SharePointContainer.Container.Resolve<Logic.IPollsSyncLogic>(new ParameterOverride("sqlRepository", sqlPollRepository), new ParameterOverride("spRepository", spPollRepository));
            logic.SyncPolls();
        }
    }
</code>```

There's a big chance I'm using Unity... wrong. Or that some other fundamental definition has been mixed up. I hope this clears up any confusion regarding the question.

答:
If the entities returned by the SharePoint repository are specific, just create a [TheEntity]Repository interface with a single implementation that talks to SharePoint.

If the [TheEntity]Repository interface has two implementations that talk respectively to SharePoint and a SQL database, you could use ResolvedParameters at configuration time (not Overrides at resolve time) to inject the right concrete repository depending on the type that is being injected into.

Edit

Seeing the code you posted, the big flaw is that you would like to use IOC and abstract repositories, but this is ruined by the fact that IPollsSyncLogic perfectly knows about Sql and Sharepoint, since its constructor has two parameters explicitly named sqlRepository and spRepository.

You should either

Fully embrace the specificity of IPollsSyncLogic as an SP to SQL synchronizer by using explicit SQL and SP repository types in its constructor signature.

or

Make IPollsSyncLogic a more abstract synchronizer between any two implementations of the same repository interface. In that case, just name its constructor parameters something like repositorySource and repositoryTarget. In your IoC configuration, use an InjectionFactory to specify the two concrete repository types.

As a side note, you should avoid resorting to Container.Resolve and rely on automatic resolution based on configuration when possible, because discrete calls to the container are usually hidden dependencies. For dependencies that are part of using statements and can't be injected through a constructor, you can rely on a Factory that produces them on the fly.

Regarding your problem with SharePoint accessing DataContext, I think it deserves a separate question.


答:
the underlying abstract reason for the correlation between compilation success and program correctness in functional programming?

Mutable State.

Compilers check things statically. They make sure your program is well formed, and the type system provides a mechanism for trying to ensure that the right sort of values are allowed in the right sort of places. The type system also tries to ensure that the right sort of semantics are allowed in the right sort of places.

As soon as your program introduces state, that latter constraint becomes less useful. Not only do you need to worry about the right values in the right spots, but you also need to account for that value changing at arbitrary points of your program. You need to account for the semantics of your code changing alongside that state.

If you're doing functional programming well, there is no (or very little) mutable state.

There is some debate though about the causation here - if programs without state work after compilation more frequently because the compiler can catch more bugs or if programs without state work after compilation more frequently because that style of programming produces less bugs.

It's likely a mix of both in my experience.

Title: Why do functional programs have a correlation between compilation success and correctness?

Body:
I've been trending toward functional programming for 4 years now, ever since I first started working with LINQ.  Recently, I wrote some pure functional C# code and I noticed, first hand, what I've been reading about functional programs - that once they compile they tend to be correct.

I tried to put a finger on why this is the case but I have not succeeded.

One guess is that in applying OO principals, you have an "abstraction layer" that isn't present in functional programs and this abstraction layer makes it possible for the contracts between objects to be correct while the implementation is wrong.

Has anyone thought about this and come up with the underlying abstract reason for the correlation between compilation success and program correctness in functional programming?


答:
These issues constitute a "technical backlog" of your project, and what I tend to do is to track them in a manner similar to the main product backlog. In many cases this will mean adding them to your ticketing/bug-tracking system like you would a user story. However, they need to be clearly marked as belonging to the technical backlog rather than the product backlog - a separate space on the wall if you have a physical backlog with sticky notes, or a separate tracker if you're using software. Some applications also allow adding tags to issues, so you could use tags, or in extreme case, use a prefix like '[TECH]' in issue title.

However, do note that some tasks you consider technical, may actually represent user stories. Non-functional requirements such as performance or stability are sometimes quite important, so something like improving response times or increasing the system's stability by extending monitoring or better testing can be quite well "sold" as user stories. It is only important that you are open with your Product Owner about the expected results and costs of implementing these changes.

Title: How to work on not User Story related tasks

Body:
I'd like to create a developer task collector where I'd put all issues that I see need some work but are not User Story related (e.g. fix some not visible quirks in startup animation, scan code with lint, enable EasyTracker in application, clean unused resources, etc.).

I don't know when we'll have time to work all those issues, maybe next Sprint we'll do one of them and two Sprints later we'll work one etc.

How to deal with it in Scrum/Sprint planning? Also should Product Owner decide what to do and when?


问:
Which according to you are the top languages to watch out for in 2011 and beyond?
Which according to you are the top languages to watch out for in 2011 and beyond?

This article  talks about 9 languages to watch out for in 2011. What are your views and inputs on this?

答:
It's all about who is demanding

People need motivation to learn languages, and without that motivation few languages are likely to become popular. Here's a quick list of the thought processes that typically apply when a developer is faced with learning a new language.

Can I easily pick this language up? (Impossible syntax implies failure)

Can I use my existing knowledge with this language? (Hey, it works on the JVM/.Net, I know those libraries inside out so I'm not a noob)

Will it pay the bills? (No jobs asking for this that are tele/commutable implies failure)

But the overriding item is simply: Who says I have to learn this, me or my boss?

If it's your boss then all other options are out the window - you will learn it. If it's you, then maybe (if you're keen) or definitely (if your ongoing work depends on it).

So what does your boss want you to learn?

The hot topics today are making highly scalable concurrent web applications that (sometimes) handle large datasets and are extremely quick to change to meet market needs. Your boss will be reading the technical literature and blogs that promote the idea that his team needs to change language to remain current in the marketplace.

Enter functional programming (F#, Erlang, Haskell, Lisp dialects) and data querying (R) languages.


答:
Explanation for managers:

A functional program is like one large machine where everything is connected, tubes, cables. [A car]

A procedural program is like a building with rooms containing a small machine, storing partial products in bins, getting partial products from elsewhere. [A factory]

So when the functional machine already fits together: it is bound to produce something.
If a procedural complex runs, you might have overseen specific effects, introduced chaos, not guaranteed the functioning. Even if you have a checklist of everything being correctly integrated, there are so many states, situations possible (partial products lying around, overflowing buckets, missing), that guarantees are hard to give.

But seriously, procedural code does not specify the semantics of the desired result as much as functional code. Procedural programmers may more easily get away by circumstantial code and data, and introduce several ways to do one thing (some of them imperfect). Typically extraneous data is created. Functional programmers might take longer when the problem gets more complex?

A strong typed functional language can still do better data and flow analysis.
With a procedural language, the goal of a program often has to be defined outside of the program, as a formal correctness analysis.


问:
how can I minimize my ajax calls to the server while creating a dashboard
I want to create a dashboard for my website. I have divided my dashboard into different modules. As I understand it, I will have to make many AJAX calls.

The different modules are:

total number of page visits changing real-time

acceptance rate

denial rate, etc...

The question I am facing is: how can I minimize my AJAX calls and is there any order in which I have to place my AJAX calls while loading the page so as to achieve minimum amount of loading time?

答:
You could build API aggregation/de-aggregation layers on both ends.

On the client-side, you can build a layer that receives API requests and "holds" them for N ms to see if up to M other requests come in. It needs to aggregate those into whatever format works for you before POSTing them. The aggregate response in whatever format is good for you will need to be split by a counterpart client layer, and the callbacks for each individual request will be issues from there.

On the server-side, you just need the corresponding de-aggregation/re-aggregation layer. Initially, you may even still process the request in a single-threaded, sequential manner. And that may even enough of a performance benefit to you. And, aggregating and "de-aggregating" requests doesn't need to be terribly complicated. You just build an array of requests and use a common serialization format (JSON) for transportation.

I've had some favorable results with a pretty simple implementation of this on a low-traffic site. (Yet to see how it scales!)

But, you may find there's no improvement at all -- you may find that, in your case, submitting N asynchronous, simultaneous-ish AJAX requests on the client-side is actually the higher-performance option. The overhead of waiting, aggregating (twice), and "de-aggregating" (twice) may be more than simply issuing multiple requests, presumably as long as those requests aren't forced to run in sequence.


问:
Communicating between unrelated components/objects
Imagine that I have a game, with Monsters, Missions, Vehicles, and of course their controllers and such, so a Monster class, Mission Controller class, Vehicle Controller class and so on.

Suppose that I need the Mission Controller to talk to Monsters. Why? Let's say when Mission A is triggered, all Monsters now turns color blue, from their original color.

There are many ways to let the Mission Controller talk to the Monster class. One way is to use the Observer pattern. The MissionController would add the Monster to its list of observers, and when the MissionController changes Missions, it tells the Monster using ONMISSIONCHANGED() or something.

The problem with that approach is why should the Monster care about MissionController? Shouldn't Monster not even know that MissionController exist? Suppose that one day, we don't want the Monster to change color, we want vehicles to do it, then we have to get rid of Monsters from the list of observers, reimplement the same thing in Vehicles and add Vehicles to the list, isn't that tedious?

Another approach is to use Singletons, there is some almighty class that has a pointer to Monsters, Vehicles, whatever. And the MissionController can just get a reference to the Monster Class immediately. But Singletons are bad, and just making Singletons for communicating between missions and monsters is just another hack.

My question is then, if the MissionController wants to set/get a property of Monster, how would it do it? How can I avoid Monster from knowing about MissionController, but yet tell the MissionController about Monster?

TL:DR - How do you allow communication between two completely unrelated objects, if you don't want them to know about each other, AND not use the Observer pattern?

EDIT:

So it seems that the idea is to use Mediator and messages, create a Mediator class, call it MissionCommunicator, and it has a list of observers where one of it would be the monster. When the MissionController wants to talk to the outside, MissionCommunicator would pass that message to the outside through IMissionMessage interface or something.

In that case, then Monster would have to implement IMissionMessage to listen to that message.

Now, imagine we have MissionController, VehicleController, AchievementController, AnimalController, etcetera.....

Suppose for some reason, Monster, for the same reason that it needs to talk to MissionController, will have to talk to all those other ones as well.

If we let Monster communicate using mediators, now we have to make a mediator for Vehicle, Achievement, Animal, blahblahblah

and Monster class becomes this:

Class Monster Implements IMissionMessage, IAchievementMessage, IAnimalMessage.....

You can of course use interface inheritance to deal with this, make a parent IMessage interface subclassing those IMissionMessage interfaces if you are using Java.

But what would be a better solution?

答:
As with all program design, if you have two things that need not know about one another (A and B) then the proper design is to have some mediator C that lives above and knows about both:

```<code>  C
 / \
A   B
</code>```

The mediator can then glue the two together via a generic decoupling mechanism (events, messages, delegates, just passing one into the other, etc). For games, the "game" is usually something that ties the different components/modules into a cohesive form. For big games, you'll usually end up with different layers of abstraction so that C can focus on two things rather than 90 things.

Body:
As with all program design, if you have two things that need not know about one another (A and B) then the proper design is to have some mediator C that lives above and knows about both:

  C
 / \
A   B

The mediator can then glue the two together via a generic decoupling mechanism (events, messages, delegates, just passing one into the other, etc). For games, the "game" is usually something that ties the different components/modules into a cohesive form. For big games, you'll usually end up with different layers of abstraction so that C can focus on two things rather than 90 things.


问:
Defining data model in Agile methodology
I always understood that in agile, each sprint is about adding a new functionality to existing application, so that the application can be build incrementally.

On the other hand, when you define data model, you need to think of many possible use cases and functionalities upfront, so that data model satisfies wide range of them and performance of CRUD operations is satisfying. This is usually a case when starting a new project. It might be hard to modify data model later, incrementally, because far too many existing functionalities might be bound to it. I'm used to waterfall methodology in this case.

So how those two conflicts methodologies can be combined together when defining an initial data model? Or there is some third way?

答:
You do just enough modeling up-front to feel comfortable moving forward responsibly. Defer as much modeling as you can until you don't feel comfortable deferring it any more.

How do you know how much can be responsibly deferred? Experience.

A basic premise behind Agile development is that you don't waste effort doing things that don't provide value. Obviously, proper data modeling provides value, and needs to be done.

But, history has proven that trying to plan/model everything up-front commonly leads to designs that, if strictly adhered to, don't end up providing the value that was expected.

Alternatively, if the plans have to change, then the effort spent on the initial design may have been essentially wasted, and could have been spent on something else.

Agile development is an art that leverages experience to minimize the wasted effort by responsibly deferring certain design decisions until those decisions need to be made, and we have the best information with which to make our decisions. That is seldom at the very beginning of a project.

If, in your case, you feel that it is irresponsible to move forward with any part of your application until your entire data model is done, then there's nothing in Agile that would keep you from doing that. But, most Agile practitioners would say that such a situation is rarely occurs.


答:
This is similar to the architecture of the application itself. Instead of doing all the architecture before starting the project, you do only what you need, and then you change it, incrementally.

The same applies to data model. If you're developing an e-commerce website and start by the functionality of displaying products, you will need the corresponding data model which describes how products are stored, but you don't need the data model of users, or shipment, or newsletters yet.

This let you focus on the actual problem you have right now (displaying the products), while keeping away of things which are not defined well yet and may change over time.

For example, your customer may decide a few weeks later that he don't need you to implement any newsletter any longer. If you've spent three hours designing the data model of newsletters before starting the project, you have wasted three hours of your time (plus the time required now to get rid of this part of the model).

Note that changing the existent schema based on the small changes in the data model can be very painful (imagine if you have to switch the IDs of products from GUIDs to bigint while your e-commerce website is already used in production). Moving from databases with strict schemas, such as Microsoft SQL, to databases which are less strict, such as MongoDB, can be a solution.

Title: Defining data model in Agile methodology

Body:
I always understood that in agile, each sprint is about adding a new functionality to existing application, so that the application can be build incrementally.

On the other hand, when you define data model, you need to think of many possible use cases and functionalities upfront, so that data model satisfies wide range of them and performance of CRUD operations is satisfying. This is usually a case when starting a new project. It might be hard to modify data model later, incrementally, because far too many existing functionalities might be bound to it. I'm used to waterfall methodology in this case.

So how those two conflicts methodologies can be combined together when defining an initial data model? Or there is some third way?


答:
In the example you give (mission controller turns monsters blue), you wouldn't need communication between the controller and the monsters. Instead the monsters could look up the "monster color" in a palette (or color table). The mission controller just sets a different value for "monster color" in the palette when the mission changes. Or switch the entire palette if the mission change affects not only monsters ...

Call the palette a style sheet and you will get the idea that a  mission change will be able to change more than just colors ...

However for your other question:

How do you allow communication between two completely unrelated
  objects, if you don't want them to know about each other, AND not use
  the Observer pattern?

In my opinion, the best way to achieve this is via events, i.e. in your example:

the monsters are subscribed on an event channel for the 'mission
change event'

the controller issues a 'mission change event' on the
event channel, and

the monsters change their color when they receive
the 'mission change event'

That way both controller and monsters don't have to know about each other. However, both have to know about the (same) 'mission change event' and the (same) event channel.

To achieve a more decoupled design, you could also combine this with the palette approach described above as follows:

a palette (or style sheet) manager is subscribed on an event channel for the 'mission change event'

the controller issues a 'mission change event' on the
event channel, and

the manager switches to a different palette (or style sheet) on receiving the 'mission change event'; the palette is chosen based on information transported in the event ...

Title: Communicating between unrelated components/objects

Body:
Imagine that I have a game, with Monsters, Missions, Vehicles, and of course their controllers and such, so a Monster class, Mission Controller class, Vehicle Controller class and so on.

Suppose that I need the Mission Controller to talk to Monsters. Why? Let's say when Mission A is triggered, all Monsters now turns color blue, from their original color.

There are many ways to let the Mission Controller talk to the Monster class. One way is to use the Observer pattern. The MissionController would add the Monster to its list of observers, and when the MissionController changes Missions, it tells the Monster using ONMISSIONCHANGED() or something.

The problem with that approach is why should the Monster care about MissionController? Shouldn't Monster not even know that MissionController exist? Suppose that one day, we don't want the Monster to change color, we want vehicles to do it, then we have to get rid of Monsters from the list of observers, reimplement the same thing in Vehicles and add Vehicles to the list, isn't that tedious?

Another approach is to use Singletons, there is some almighty class that has a pointer to Monsters, Vehicles, whatever. And the MissionController can just get a reference to the Monster Class immediately. But Singletons are bad, and just making Singletons for communicating between missions and monsters is just another hack.

My question is then, if the MissionController wants to set/get a property of Monster, how would it do it? How can I avoid Monster from knowing about MissionController, but yet tell the MissionController about Monster?

TL:DR - How do you allow communication between two completely unrelated objects, if you don't want them to know about each other, AND not use the Observer pattern?

EDIT:

So it seems that the idea is to use Mediator and messages, create a Mediator class, call it MissionCommunicator, and it has a list of observers where one of it would be the monster. When the MissionController wants to talk to the outside, MissionCommunicator would pass that message to the outside through IMissionMessage interface or something.

In that case, then Monster would have to implement IMissionMessage to listen to that message.

Now, imagine we have MissionController, VehicleController, AchievementController, AnimalController, etcetera.....

Suppose for some reason, Monster, for the same reason that it needs to talk to MissionController, will have to talk to all those other ones as well.

If we let Monster communicate using mediators, now we have to make a mediator for Vehicle, Achievement, Animal, blahblahblah

and Monster class becomes this:

Class Monster Implements IMissionMessage, IAchievementMessage, IAnimalMessage.....

You can of course use interface inheritance to deal with this, make a parent IMessage interface subclassing those IMissionMessage interfaces if you are using Java.

But what would be a better solution?


答:
You could use an EventBus.

When using a bus system, components in your application can register for events that are fired by other components.
This way a monster could fire a MovedEvent ore something that contains the necessary data.

There are several implementations in several languages.

In java, commonly used one is part of guava: https://code.google.com/p/guava-libraries/wiki/EventBusExplained

If you are serious about the whole thing you should also consider using an EntitySystem (that's backed up by an Event bus)

See fir example http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/ for more info on that.

You're basically not subclassing, but composing your game entities. That makes it rather flexible.
The logic is executed by so called Systems - and these could communicate via an EventBus.


问:
type infered statically typed languages?
are there any typeless typesafe languages? By typesafe I mean types are checked at compile time. By typeless I mean types are not declared.

I know this is easier than it sounds, maybe even impossible but for example if I had code like this

```<code>foo = {
   bar: 123;
}
</code>```

In some imaginary language I can possibly know that bar is an int and foo is a struct/object/class with 1 int field.

Similarly if I do this

```<code>SomeFunc(v) {
  printInt(v.bar);
}
</code>```

And elsewhere I do this

```<code>SomeFunc(foo);
</code>```

All of that seems type checkable at compile time. With enough context it might even be type checkable across compilation units.

Are there any languages that have attempted this? Basically make it possible to rarely declare types and yet still be typesafe at compile time ?

答:
Yes, pretty much everything in the Haskell/ML family does this. Here's a snippet of some relevant Haskell

```<code> foo = 1 + bar
 bar = "Not a number :O"
 main = putStrLn foo
</code>```

No types need to be explicitly annotated, but the error is still caught at compile time. In general we always infer some types in every language. Nothing would require something like

```<code>int bar = 1;
foo((bar : int) + (1 : int) : int) : string
</code>```

Everyone supports at least inferring the types for subexpressions because otherwise the language is just unwritable. Usually the typechecker that the compiler runs will annotate the abstract syntax tree with these types. Only a few languages support global type inference, where we need write no types at all. There are some features which in general make complete type inference either difficult or impossible. An incomplete list

Subtyping

Polymorphism of rank 3 or higher

Dependent types

A completely monomorphic language (This is actually just ambiguous without some annotations)

PS I just wanted to make a note on terminology: type safe usually means that a well typed program always has defined behavior. Python is type safe and dynamically typed, C is not type safe and is statically typed.

I think what you want to say is a statically typed language that requires no type annotations :)

Body:
Yes, pretty much everything in the Haskell/ML family does this. Here's a snippet of some relevant Haskell

 foo = 1 + bar
 bar = "Not a number :O"
 main = putStrLn foo

No types need to be explicitly annotated, but the error is still caught at compile time. In general we always infer some types in every language. Nothing would require something like

int bar = 1;
foo((bar : int) + (1 : int) : int) : string

Everyone supports at least inferring the types for subexpressions because otherwise the language is just unwritable. Usually the typechecker that the compiler runs will annotate the abstract syntax tree with these types. Only a few languages support global type inference, where we need write no types at all. There are some features which in general make complete type inference either difficult or impossible. An incomplete list

Subtyping

Polymorphism of rank 3 or higher

Dependent types

A completely monomorphic language (This is actually just ambiguous without some annotations)

PS I just wanted to make a note on terminology: type safe usually means that a well typed program always has defined behavior. Python is type safe and dynamically typed, C is not type safe and is statically typed.

I think what you want to say is a statically typed language that requires no type annotations :)


答:
Type inference does exactly this. You do not generally have to declare types, as they can be inferred from usage. However, more complex type systems will still occasionally require explicit type annotations.

Your example can be written in Standard ML as

```<code>fun some_func {bar} = print (Int.toString bar);

val foo = {bar = 123};
some_func foo;
</code>```

This uses pattern matching to obtain the bar field in the record passed to the some_func. The ML language pioneered type inference, but type inference is becoming a more common sight with various levels of support in Haskell, C++, C#, and Scala.

Title: type infered statically typed languages?

Body:
are there any typeless typesafe languages? By typesafe I mean types are checked at compile time. By typeless I mean types are not declared.

I know this is easier than it sounds, maybe even impossible but for example if I had code like this

```<code>foo = {
   bar: 123;
}
</code>```

In some imaginary language I can possibly know that bar is an int and foo is a struct/object/class with 1 int field.

Similarly if I do this

```<code>SomeFunc(v) {
  printInt(v.bar);
}
</code>```

And elsewhere I do this

```<code>SomeFunc(foo);
</code>```

All of that seems type checkable at compile time. With enough context it might even be type checkable across compilation units.

Are there any languages that have attempted this? Basically make it possible to rarely declare types and yet still be typesafe at compile time ?

Body:
Type inference does exactly this. You do not generally have to declare types, as they can be inferred from usage. However, more complex type systems will still occasionally require explicit type annotations.

Your example can be written in Standard ML as

fun some_func {bar} = print (Int.toString bar);

val foo = {bar = 123};
some_func foo;

This uses pattern matching to obtain the bar field in the record passed to the some_func. The ML language pioneered type inference, but type inference is becoming a more common sight with various levels of support in Haskell, C++, C#, and Scala.


问:
In what way are union types better for correctness than a common interface?
I've just recently started familiarising myself with functional programming, mostly via F#, and there's one particular functional idiom that I'm not fully understanding the benefits of. I've seen it described in a few places, but I'll refer to the version in this article.

The article describes a shopping cart with several requirements, which essentially put it in one of three states: Empty, Active (occupied by one or more items but not yet paid for), or PaidFor. It's argued that by using F#, it's easy to ensure correctness because the compiler will prevent you from performing illegal operations on cart states. For example:

```<code>let addItemToCart cart item =
   match cart with
   | Empty state -> state.Add item
   | Active state -> state.Add item
   | PaidFor state ->
       printfn "ERROR: The cart is paid for"
       cart
</code>```

Only the Empty and Active states have Add methods attached, so if we tried to instead write:

```<code>| PaidFor state -> state.Add item
</code>```

or similar, we'd get a compiler error.

By comparison, an OO approach might (in C#) look like:

```<code>interface ICart
{
    ICart AddItem(CartItem item);
}

class EmptyCart : ICart
{
    public ICart AddItem(CartItem item)
    {
        return new ActiveCart(item);
    }
}

class ActiveCart : ICart
{
    public ICart AddItem(CartItem item)
    {
        return new ActiveCart(_items.Add(item));
    }
}

class PaidForCart : ICart
{
    public ICart AddItem(CartItem item)
    {
        throw new InvalidOperationException("Who cares about Liskov anyway?");
    }
}
</code>```

What I'm trying to understand is what benefit a client gets from having addItemToCart rather than ICart.AddItem. Either way, there's no compile-time check stopping the client from using that function with a paid for cart. And either way, the client has no control over what happens in the error case.

The functional version could be modified to give some control to the client over what happens in the error case (a callback, or some wrapper type over the result), but the object-oriented could be modified to do so just as easily (maybe with a TryAddItem method, which would be a bit more OO-idiomatic).

So what am I missing?

Edit

It was mentioned that in the comments that in the C# version, anyone could create an ICart implementation. To address that: an alternative version would be to replace ICart with an abstract Cart class and make its constructors internal. This isn't ideal and in some situations may not be feasible, but I think in the general case it works pretty well.

答:
There is no benefit from from having addItemToCart rather than ICart.AddItem.  They are essentially identical.  Both of those necessarily have a runtime check, because you want to be able to have a variable with any kind of Cart in it, and you won't know at compile time which one will get passed into the function.

Where the benefit comes is when you first implement addItemToCart, or later when you add another operation at the same level of abstraction, say oneClickAddAndPay.  The union type will give you a compile error if you try to Add an item to a PaidFor cart, or if you completely forget to account for PaidFor carts at all.  The ICart interface can't catch that kind of programming error at compile time.

In other words, the union type can't move all kinds of errors to compile time, but it does move some.  If you don't end up adding a lot of functions like oneClickAddAndPay that reuse the existing Add functionality, it won't buy you much.


问:
Can we technically un-blur images?
Since there is an algorithm to blur images, so that part of it cannot be recognised, can we reverse the algorithm and unblur part of than image?

Is there a program that already does that, is that even possible, even in a near future?

答:
In the article Why blurring sensitive information is a bad idea the authors describe an method of 'unblurring' numbers and text.

The process is similar to a dictionary attack: you make blurred images (of similar pattern) from characters/numbers and then match these with the blur.

Title: Can we technically un-blur images?


问:
Provide web images with high resolution and let the browser scale it. A bad idea?
Back in the old days when I learned to create web pages, the rule of thumb was: Don't resize your images with HTML/CSS, provide the image in its "native" resolution. Otherwise, it will be upscaled or downscaled by the browser and the image will look blurry or ugly.

Those were the days when we didn't have high-resolution tablets, huge screens and browsers with built-in zoom functionality using smart algorithms.

My gut feeling tells me that a lot of people don't have their browser at a zoom factor of 100%, so browser-side scaling is going to happen anyway -- providing a high-resolution source should lead to a strictly better result than the native-for-100%-version in that case. Have we reached the time yet where it makes sense to provide images with higher resolution¹ than required when designing new web sites?

¹ ...within reasonable limits considering the users' bandwidth, of course.

答: Most of the new front-end designs I've seen are doing a lot of this nowadays. It seems to work generally OK -- browser resamplers have got much better, pipes are fatter and images are heftier so you aren't trying to re-raster a 10kb JPEG. I've seen a few downsides -- the big ones being file sizes are bloated which effects visible performance, especially on mobile networks. Also, we had one designer who fell in love with massive, resizing background animated gifs. That melted certain browsers at times.</p>


问:
Encapsulate one business story/use case in one class?
I don't like classes like *Service, with bunch of business methods - aka anemic model. I was thinking, instead, to have a class per use case. This was inspired (if not the same) from CQRS. Even if we are not using event sourcing, I believe that this kind of encapsulation would make sense. Then the service layer (application layer) would simple consist of commands that user can instantiate and pass to some executer.

Would this make sense?

Here are some requirements (example):

user creates a poll with a question and at least 2 choices

user updates poll and choices; choices can be only added

user may vote for a choice, question update time must be updated

etc.

These are business scenarios/use cases - however you want to call them. They contain business logic (like we need at least 2 choices etc). I was thinking in:

```<code>public class CreatePollCommand implements Command {

    @Inject
    Repository_Validator_whatever_infrastructure_we_need

    public CreatePollCommand(input_arguments) {
    }

    public void execute() {
        // write business logic here
    }
}
</code>```

And this can be used from presentation layer:

```<code>executor.run(new CreatePollCommand(input_from_ui));
</code>```

Then executor injects whatever he needs to inject and thats it.

答:
The presence of a service layer does not necessarily imply the model is anemic. A service layer might provide a simplified facade to a complex domain model. I.e. a business user may just want to create a new poll. The UI is simplified if it speaks in those terms and the service layer would translate from what the UI understands into operations leveraging the domain model.

Whether it is an executor interpreting Commands or calls on a service layer in the end someone will perform operations against the domain model.

Now if the executor/service layer is responsible for doing all the CRUD on the objects to perform the transaction, then you have an anemic model.

Let's make an example.

Your model on the backend will have a Poll with Questions that have Answers there will be an Owner for the poll (most likely the person creating it) along with a number of other objects created (billing, auditing, etc.) that the User might not see. The Poll might have a certain number of allowed Respondents (identified by an email list) and Invitations might have to be generated for the respondents (emails)

Now imagine if your executor was responsible for generating all of those objects directly and linking them together...that would be an anemic model. A robust model would use the Aggregate root to handle all of the required operations.

For example the Executor might get the Account that the poll will be created under and call

```<code>var poll =Account.CreatePoll(cmd.PollName, cmd.CampaignId /*you get the point*/);
</code>```

The Account object would be responsible for creating the poll and tying it to the account, campaign, and other details that it understands about how its polls operate. It would also add the poll to its Polls collection.

Next the executor would perform the rest of its operations on the Poll returned from the prior call.

```<code>foreach (var question in cmd.Questions)
{
  poll.AddQuestion(question.Prompt, question.Answers);
}

//cmd.Respondents is a comma separated list of strings containing respondent emails
//or a list of emails
poll.AddRespondents(cmd.Respondents);
unitOfWork.Commit();
</code>```

As you see the robust model takes simple objects and constructs the appropriate domain objects according to internal logic. With an anemic model, the executor or service layer would be responsible for instantiating each question and adding it to a Poll.Questions property. And doing the same with the Answers. There might even be intermediate objects between the questions and poll that the poll would be responsible for constructing because it owns its aggregate.

Either way you slice it, the command or service layer is designed to simplify the complexity of the domain for its clients.

Body:
The presence of a service layer does not necessarily imply the model is anemic. A service layer might provide a simplified facade to a complex domain model. I.e. a business user may just want to create a new poll. The UI is simplified if it speaks in those terms and the service layer would translate from what the UI understands into operations leveraging the domain model.

Whether it is an executor interpreting Commands or calls on a service layer in the end someone will perform operations against the domain model.

Now if the executor/service layer is responsible for doing all the CRUD on the objects to perform the transaction, then you have an anemic model.

Let's make an example.

Your model on the backend will have a Poll with Questions that have Answers there will be an Owner for the poll (most likely the person creating it) along with a number of other objects created (billing, auditing, etc.) that the User might not see. The Poll might have a certain number of allowed Respondents (identified by an email list) and Invitations might have to be generated for the respondents (emails)

Now imagine if your executor was responsible for generating all of those objects directly and linking them together...that would be an anemic model. A robust model would use the Aggregate root to handle all of the required operations.

For example the Executor might get the Account that the poll will be created under and call

var poll =Account.CreatePoll(cmd.PollName, cmd.CampaignId /*you get the point*/);

The Account object would be responsible for creating the poll and tying it to the account, campaign, and other details that it understands about how its polls operate. It would also add the poll to its Polls collection.

Next the executor would perform the rest of its operations on the Poll returned from the prior call.

foreach (var question in cmd.Questions)
{
  poll.AddQuestion(question.Prompt, question.Answers);
}

//cmd.Respondents is a comma separated list of strings containing respondent emails
//or a list of emails
poll.AddRespondents(cmd.Respondents);
unitOfWork.Commit();

As you see the robust model takes simple objects and constructs the appropriate domain objects according to internal logic. With an anemic model, the executor or service layer would be responsible for instantiating each question and adding it to a Poll.Questions property. And doing the same with the Answers. There might even be intermediate objects between the questions and poll that the poll would be responsible for constructing because it owns its aggregate.

Either way you slice it, the command or service layer is designed to simplify the complexity of the domain for its clients.


问:
Best way to handle delimited files
So typically a CSV file uses a comma and the return character as it's field and line delimiters.

This runs into obvious problems with text which can contain both these characters.

Obviously there are options there (escaping them) but how do people handle this?  Use different characters - pipes or tildas?  Escape them?  Not use delimited files, after all it's 2010 and we have XML now?

Looking at least effort for a decent chance of not seeing problems.

(Just to be clear, this is a question out of curiosity rather than something more solid - it's something I've come up against time and time again playing with data, always got round it but it normally feels a bit, well, dirty, and wondered what other people's experience was).

答:
CSV is still a valid format in many situations, especially since it's still got to be the easiest way for a customer to write data that needs to be imported into your application.  Few of our customers like to deal with XML, perhaps because it's very verbose and has all of those  "scary" angle brackets.  It's so much simpler for them to wrap their brains around a simple list of items separated by an agreed upon character, and also agree that the same character will not be allowed in the contents of a field.

That said, you still have to handle the input correctly and check for situations where they use invalid characters.  I've started to use FileHelpers for my CSV parsing needs.

Title: Best way to handle delimited files


问:
What is the justification for the running time of this loop?
I don't understand why the running time of the following loop is n+2 ? Also why the running time of the statements inside the loop is n+1 ?</p>

```<code>Double test(int n){
      int sum=0;  -> 1 time
      int i;  -> 0 time
      for(i=0; i<=n;i++)  -> n+2 times
      {
        scanf("%d",&a);  -> n+1 times
        sum=sum+a;  -> n+1 times
      }
      return sum;  -> 1 time
    }
</code>```

答: The body of loop you've written is entered n+1 times (i from 0 to n), after that the variable i is incremented again, it's value now becomes n+1. Then it is compared to n ( i <= n ), this test fails and the body of the loop is skipped.


答: The answers so far have mentioned extreme functional languages.  If you're looking for something a bit closer to the mainstream, have a look at Boo.  Its syntax is heavily inspired by Python, but it's statically typed.  Type declarations are required for defining class members, but for variables, method arguments and return types everything can be optionally given an explicit type, or type-inferenced if none is provided.</p>


答:
To put it simply, the restrictions mean there are fewer correct ways to put things together, and first-class functions make it easier to factor out things like loop structures.  Take the loop from this answer, for example:

```<code>for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        iterator.remove();
    }
}
</code>```

This happens to be the one safe imperative way in Java to remove an element from a collection while you're iterating through it.  There are lots of ways that look very close, but are wrong.  People unaware of this method sometimes go through convoluted ways to avoid the problem, like iterating through a copy instead.

It's not terribly difficult to make this generic, so it will work on more than just collections of Strings, but without first-class functions, you can't replace the predicate (the condition inside the if), so this code tends to get copied and pasted and modified slightly.

Combine first-class functions that give you the ability to pass the predicate in as a parameter, with the restriction of immutability that makes it very annoying if you don't, and you come up with simple building blocks like filter, as in this Scala code that does the same thing:

```<code>list filter (!_.isEmpty)
</code>```

Now think about what the type system checks for you, at compile time in the case of Scala, but these checks are also done by dynamic type systems the first time you run it:

list must be some sort of type that supports the filter method, namely a collection.

The elements of list must have an isEmpty method that returns a boolean.

The output will be a (potentially) smaller collection with the same type of elements.

Once those things have been checked, what other ways are left for the programmer to screw up?  I accidentally forgot the !, which caused an extremely obvious test case failure.  That's pretty much the only mistake available to make, and I only made it because I was directly translating from code that tested for the inverse condition.

This pattern is repeated over and over again.  First-class functions let you refactor things out into small reusable utilities with precise semantics, restrictions like immutability give you the impetus to do so, and type checking the parameters of those utilities leaves little room to screw them up.

Of course, this is all dependent on the programmer knowing that the simplifying function like filter already exists, and being able to find it, or recognizing the benefit of creating one yourself.  Try to implement this yourself everywhere using only tail recursion, and you're right back in the same complexity boat as the imperative version, only worse.  Just because you can write it very simply, doesn't mean the simple version is obvious.

Body:
To put it simply, the restrictions mean there are fewer correct ways to put things together, and first-class functions make it easier to factor out things like loop structures.  Take the loop from this answer, for example:

for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        iterator.remove();
    }
}

This happens to be the one safe imperative way in Java to remove an element from a collection while you're iterating through it.  There are lots of ways that look very close, but are wrong.  People unaware of this method sometimes go through convoluted ways to avoid the problem, like iterating through a copy instead.

It's not terribly difficult to make this generic, so it will work on more than just collections of Strings, but without first-class functions, you can't replace the predicate (the condition inside the if), so this code tends to get copied and pasted and modified slightly.

Combine first-class functions that give you the ability to pass the predicate in as a parameter, with the restriction of immutability that makes it very annoying if you don't, and you come up with simple building blocks like filter, as in this Scala code that does the same thing:

list filter (!_.isEmpty)

Now think about what the type system checks for you, at compile time in the case of Scala, but these checks are also done by dynamic type systems the first time you run it:

list must be some sort of type that supports the filter method, namely a collection.

The elements of list must have an isEmpty method that returns a boolean.

The output will be a (potentially) smaller collection with the same type of elements.

Once those things have been checked, what other ways are left for the programmer to screw up?  I accidentally forgot the !, which caused an extremely obvious test case failure.  That's pretty much the only mistake available to make, and I only made it because I was directly translating from code that tested for the inverse condition.

This pattern is repeated over and over again.  First-class functions let you refactor things out into small reusable utilities with precise semantics, restrictions like immutability give you the impetus to do so, and type checking the parameters of those utilities leaves little room to screw them up.

Of course, this is all dependent on the programmer knowing that the simplifying function like filter already exists, and being able to find it, or recognizing the benefit of creating one yourself.  Try to implement this yourself everywhere using only tail recursion, and you're right back in the same complexity boat as the imperative version, only worse.  Just because you can write it very simply, doesn't mean the simple version is obvious.


问:
Transitions taking place in NFA
While studying about NFA and DFA in Compiler Design I couldn't get how they converted an regular expression to NFA as shown in NFA.I would like to know why there is an epsilon transition between (8 -> 10) and (9 -> 10).

Because I think even if we don't write states 9 and 10 the NFA would be unaffected.  Can anyone tell me whether this is correct to do like that?

答:
Without states 9 and 10, we need a new start and accept state.  Lets assume that these are states 7 for start (because there is an ε transition from 9 to 7) and 8 for accept (because there is an ε from 8 to 10).

However, this doesn't match the empty string anymore.

The diagram shown is the regular expression /^(ab|c)*$/.  Without states 9 or 10 and the transition, the regular expression representing this NFA would be /^(ab|c)+$/ which is different.

Title: Transitions taking place in NFA


问:
I'm graduating with a Computer Science degree but I don't feel like I know how to program
I'm graduating with a Computer Science degree but I see websites like Stack Overflow and search engines like Google and don't know where I'd even begin to write something like that. During one summer I did have the opportunity to work as a iPhone developer, but I felt like I was mostly gluing together libraries that other people had written with little understanding of the mechanics happening beneath the hood.

I'm trying to improve my knowledge by studying algorithms, but it is a long and painful process. I find algorithms difficult and at the rate I am learning a decade will have passed before I will master the material in the book. Given my current situation, I've spent a month looking for work but my skills (C, Python, Objective-C) are relatively shallow and are not so desirable in the local market, where C#, Java, and web development are much higher in demand. That is not to say that C and Python opportunities do not exist but they tend to demand 3+ years of experience I do not have. My GPA is OK (3.0) but it's not high enough to apply to the large companies like IBM or return for graduate studies.

Basically I'm graduating with a Computer Science degree but I don't feel like I've learned how to program. I thought that joining a company and programming full-time would give me a chance to develop my skills and learn from those more experienced than myself, but I'm struggling to find work and am starting to get really frustrated.

I am going to cast my net wider and look beyond the city I've grown up in, but what have other people in similar situation tried to do? I've worked hard but don't have the confidence to go out on my own and write my own app. (That is, become an indie developer in the iPhone app market.) If nothing turns up I will need to consider upgrading and learning more popular skills or try something marginally related like IT, but given all the effort I've put in that feels like copping out.

答:
Khilon's answer is what I was going to answer but with an extra clarification; in my view, graduating with a degree in computer science or engineering or any other discipline qualifies you to begin your apprenticeship in your chosen field.

We don't have formal apprenticeships in the software development field but ideally, during the years following your graduation, you will learn lots of techniques that will help with the final goal of delivering robust code that is maintainable, possible to debug, predictable, understandable by others and generally reliable. This includes topics such as testing strategies, build management, configuration management, version control, defect tracking, quality metrics etc. etc.

If you understand computing theory, complexity theory, algorithms etc. then you will have a strong BS detector which is one of the great things that you get from a good degree. If you can then work with a good team that understands the engineering aspects of software development then you will have a very good combination of knowledge.


问:
ClamAV Database Usage Policy?
What about if I sell computers with embedded home-made antivirus using ClamAV database as its main database or as optional database? Of course the software isn't open-source/GPL.

Is it allowed?

Many thanks.

答:
If you can read the database without using GPL code (borrowed from ClamAV or obtained elsewhere), and if the license of the database itself allows it, then you can use the database as input for your non-free application.

If you can't read the database without using GPL code, then that GPL code forces you to release your application under the GPL as well.

In general, an application and the data it uses are considered separate unrelated works under copyright law, so their licenses generally don't affect each other and don't need to be compatible.

For that reason, the license on the ClamAV database can be very different and much more restrictive than the license on the ClamAV application. If you want to use the database, be sure to check under what terms it is being distributed.

Title: ClamAV Database Usage Policy?


问:
I want to understand clearly why can't we instantiate an object of an abstract class
Can I get a clear explanation why why can't we instantiate an object of an abstract class. I know abstract is not real. But I want to know more why can't we instantiate an object of an abstract class. </p>

答: Let me answer your question with another question: What would happen when you call any of the abstract methods?</p>


答:
Because an abstract class by design usually has a unimplemented method. What should the program do if someone tried to call it?

Having unimplemented methods on an object is usually a bug so the compiler helps you by not allowing them to exist.

If you want to throw an error when the method is called then just implement it with just throws new UnsupportedOperationException(); as the implementation.

If you don't want to create a new class you can instead use an anonymous class:

```<code>AbstractFoo foo = new AbstractFoo(param, for, constructors){
   @Override
   public void foo(){
       //override and implement methods
   }
};
</code>```

This will create a concrete class behind the scenes which will be used.

Title: I want to understand clearly why can't we instantiate an object of an abstract class

Body: Can I get a clear explanation why why can't we instantiate an object of an abstract class. I know abstract is not real. But I want to know more why can't we instantiate an object of an abstract class. </p>

Body:
Because an abstract class by design usually has a unimplemented method. What should the program do if someone tried to call it?

Having unimplemented methods on an object is usually a bug so the compiler helps you by not allowing them to exist.

If you want to throw an error when the method is called then just implement it with just throws new UnsupportedOperationException(); as the implementation.

If you don't want to create a new class you can instead use an anonymous class:

AbstractFoo foo = new AbstractFoo(param, for, constructors){
   @Override
   public void foo(){
       //override and implement methods
   }
};

This will create a concrete class behind the scenes which will be used.


答:
It's because an abstract class isn't complete. One or more parts of its public interface are not implemented. You've said what they're going to be - what they're called, what their name is, what they return - but no implementation has been provided, so nobody would be able to call them.

Compilers prevent you from instantiating such incomplete objects on the basis that if you do instantiate an object you're going to want to use its entire public interface (this assumption is related to the idea that an object should do a minimal set of things, so that the public interface is not too large to manage). It's also a useful safety net. The compiler says "hang on, this is just part of a class, you need to provide the rest of it".

Say the C# compiler was modified to allow you to instantiate abstract classes. Presumably it would fill in the missing definitions with some stub code. This being C#, I suspect that code would just throw System.NotImplementedException. This is not particularly useful, and also an error you wouldn't be able to find until runtime. Finding it a compile time is far more likely to get you a program that works.

And that's not even thinking about the possibility that one of the concrete methods provided by the abstract class happens to call one of the abstract ones that you decided you didn't need to write.


问:
How to solicit new product recommendations from existing clients?
My company is working on developing a new product that is similar (but larger in scope) than our existing, primary application. It will incorporate most of the functionality of our current application (except where that functionality isn't currently being used) and eventually supplant it.

Our initial thought was to solicit product suggestions and feedback on mock-ups from certain members of our current clientele who have made multiple feature suggestions in the past. This seemed good in theory, as we could get a larger perspective from our projected user base as well as getting buy-in from those customers who might have had feature requests they previously made indefinitely postponed.

In practice what we're getting is a lot of silence. We have meetings with this group every two weeks to get their feedback and suggestions. However, they rarely - if ever - have anything to add. We've tried emailing out to them a few weeks in advance, asking for their suggestions on a certain feature that we intend to design and mock-up for them on x date, and no suggestions come back to us. When we ask for feedback on existing mock-ups during the meetings, the response is always along the lines of "Oh, that looks good...I'll get back to you if I think of any problems." This leaves us extremely anxious.

TLDR: The concern is that while our design may look great to us and our business team, our customer base won't like it (there are many areas it is radically different, based on things we implemented poorly the first time around). Can anyone offer any suggestions on ways we can better solicit feedback?

Edit: Please note that I'm not asking how to proceed without client involvement. Rather, I'm looking for suggestions on how to convince people that it's in their best interest to be more involved.

答: You will probably get lots of more feedback as soon as your new product is on-line and people start using it. Especially, when you replace your existing application, so your clients are not able to use the old one any more. So work towards that goal - give your clients a version of the new product at hand with access to the same feature-scope they had in the old application (hopefully you have prepared your new application for such a scenario?) Not just mock-ups - they have to work with that thing. If your new product is not ready for that step, try to make some working parts of it available to your client and replace the older parts with these new ones. Or make something like a "beta" program, where volunteers can try out your new application for free (!).


问:
What is the HTML 4 DTD role in HTML5
All, I know there are three types of DTD for HTML 4.01 (strict, transitional, and frameset). And I knew the DTD defines the syntax of markup constructs and the document structure with a list of legal elements and attributes.

So why is DTD missing in HTML 5? Isn't it necessary for HTML 5 document? Or no need to specify DTD for HTML5 because of only one DTD for HTML 5 by default ? Any special reason for removing DTD for HTML5?

Thanks

答: HTML5 is not an application of SGML, therefore it doesn't need an SGML DTD. I'm pretty sure that there are some things in HTML5 that are illegal in SGML, so even if you wanted to, you couldn't create an SGML DTD for HTML5.</p>

Title: What is the HTML 4 DTD role in HTML5