答:
You are mixing up two concepts: indexing and identity.  They are not the same thing and should not be confused.

What is the purpose of indexing? Fast random access.  If the performance isn't an issue, and given your description it isn't, then using a collection that has an index is unnecessary and probably accidental.

If you (or your team) is being confused by the index vs the identity, then you can solve that problem by not having an index.  Use either a dictionary or an enumerable and get the channel by value.

```<code>channels.First(c=> c.Number == identity).SomeProperty = newValue;
channels[identity].SomeProperty = newValue;
</code>```

The first is more clear, the second is shorter -- they may or may not get translated into the same IL, but either way, given you are using this for a dropdown, it should be fast enough.

Body:
You are mixing up two concepts: indexing and identity.  They are not the same thing and should not be confused.

What is the purpose of indexing? Fast random access.  If the performance isn't an issue, and given your description it isn't, then using a collection that has an index is unnecessary and probably accidental.

If you (or your team) is being confused by the index vs the identity, then you can solve that problem by not having an index.  Use either a dictionary or an enumerable and get the channel by value.

channels.First(c=> c.Number == identity).SomeProperty = newValue;
channels[identity].SomeProperty = newValue;

The first is more clear, the second is shorter -- they may or may not get translated into the same IL, but either way, given you are using this for a dropdown, it should be fast enough.


问:
Can you do iterative development in c#?
I'm primarily a Python/R developer. In those languages, the way I develop is to sketch out a data and class structure, write the methods and their tests in interactive mode, then refactor them up into class methods and properties and sort out the tests. Some friends are suggesting I learn C#. I don't do much work with complied/staticly typed languages.

Can I develop in an 'interactive mode' the same way in C# - that is, load in some sample data, write methods interactively to ensure they're working right, then push methods up to classes as they're completed? Or is this not a natural way to develop in a compiled language?

答:
Whenever I have small code snippets that I'd like to test, I personally enjoy using .Net Fiddle.

Don't forget you can always spin up small projects like a C# console app to do fairly straightforward things. This may be especially necessary if you need to use third party libraries.

ContentLicense: CC BY-SA 3.0

Title: Can you do iterative development in c#?


答:
The kind of iterative development you're speaking of is typically done via Unit Tests in C#.

Add a Unit Test project to your solution.

Add aUnit Test class to the test project.

Define the public API you want to create.

Write a test to exercise one of the class's members.

Run the tests. It should fail.

Implement the functionality.

Run the tests. If green, great! If red, GoTo #6.

Repeat.

Title: Can you do iterative development in c#?

Body:
I'm primarily a Python/R developer. In those languages, the way I develop is to sketch out a data and class structure, write the methods and their tests in interactive mode, then refactor them up into class methods and properties and sort out the tests. Some friends are suggesting I learn C#. I don't do much work with complied/staticly typed languages.

Can I develop in an 'interactive mode' the same way in C# - that is, load in some sample data, write methods interactively to ensure they're working right, then push methods up to classes as they're completed? Or is this not a natural way to develop in a compiled language?


问:
Async library guidance

I'm creating a library that contains a class that exposes several Async methods:

public class MyClass {
  public async Task<Foo> DoFooAsync() { /*...*/ }
  public async Task<Bar> DoBarAsync() { /*...*/ }
}
```

I have two (main) questions about this:

I understand that not everybody likes to (or needs to) work asynchronously; it's easy for someone using my library to invoke these methods synchronously. However, it won't be very much of an effort to provide synchronous wrappers for the async method so that the class also provides a public Foo DoFoo() and public Bar DoBar() method.

Should I provide these methods or should I let people implement their own?

If I provide these methods, should I:

Create a private T ExecuteFunctionSynchronously<T>(Func<T> func) method and have the synchronous methods invoke this ExecuteFunctionSynchronously internally or ...

...should every synchronous method just call the async method 'waterfall style' (so DoFoo() executes return DoFooAsync().Result (or something like that) internally?

The class will, later, have a 'message loop' which continually reads data coming from an (awaited) socket. I want this message loop to go on 'eternally'. I want the class to be easily used by everyone.

What kind of 'style' should I use for this messageloop to notify users of MyClass that something has happened?

Events (e.g. MyClass.FooReceived += myhandler)?

Callbacks (e.g. MyClass.StartListening(myhandler))?

Something 'awaitable' (e.g. while (await MyClass.GetFoo()) { ... })?

Reactive (Rx)?

Something other than above, namely ...

I'm primarily asking for "style" guidance; how would you approach this and how do you think a (primarily) async library should provide (API wise) interaction while keeping internals and messageloops out of the user's mind without exposing too much of what's going on internally.

答:
Should I provide these methods or should I let people implement their own?

You should avoid doing that. Stephen Toub explains why in his article Should I expose synchronous wrappers for asynchronous methods? The reason why is that doing this has quite a few pitfalls, simple .Result may appear to work for you, but may fail (or rather, deadlock) in other situations.

What kind of 'style' should I use for this messageloop to notify users of MyClass that something has happened?

I think that depends on what kind of notifications are you exposing, what will your users want to do with them and what will feel most natural to them. There is a reason why all of those different styles exist.

Title: Async library guidance

ContentLicense: CC BY-SA 4.0


问:
What is more pythonic - subclassing dict or creating external functions to manipulate them?
Say I have a dictionary that contains complex classes that need to be loaded and unloaded in a special way. (Not especially special, just outside the bounds of this question.) Should I gracefully subclass the built-in dict like this:

```<code>class ExampleClass(dict):
    def __str__(self):
        return 'ExampleClass; '+dict.__str__(self)

    @classmethod
    def loads(cls, string):
        <load object from string here>

    def dumps(self):
        <dump object here>
</code>```

Or do something like this:

```<code>def load_special_structure(string):
    <load object from code here>

def dump_special_structure(obj):
    <dump object here>
</code>```

That's all the extra functionality I need. It's not too pythonic to have to use a special imported method to dump and load it, but subclassing a dictionary isn't either. On the usage perspective, being able to import that class, load it from a string and use it like a dictionary is really useful.

答: In general, in Python I favor using functions over subclassing internal classes. In the end, if you write your String -> dict method, you end up working with a dict, pure as the driven snow. Just put your functions in a sensible module and import them only where needed; this will also encourage you not to import the functions everywhere, which will help you out by keeping the IO separated from your logic.


问:
In C, how are functions accessible if they're not inline or called by #include?
I'm looking at code that somehow calls a library but I don't see it calling any of the library's headers at any point.  I've done searches within the code and I don't see anywhere the functions, typedefs or structs getting defined anywhere...yet it compiles and works, and LDD shows it calling the library.  What is it that's inherent to the C language that allows this to work?

Code that references functions/typedefs/structs non-existent elsewhere in code:

```<code>typedef struct pngbuffer_s
{
    byte *buffer;
    png_size_t size, offset;
} pngBuffer_t;
</code>```

答: C assumes that undeclared functions take an arbitrary number of arguments and return an int. Undefined typedefs and structs should always cause an error. My guess would be that one of the files you do include contains the necessary include directive for this library. Most compilers support an option to print out which headers they include as they go through compilation.</p>


问:
UnsupportedOperationException in java collections framework interfaces
Looking through the Java Collections Framework, I've noticed quite a few of the interfaces have the comment (optional operation). These methods allow implementing classes to through an UnsupportedOperationException if they just don't want to implement that method.

An example of this is the addAll method in the Set Interface.

Now, as stated in this series of questions, interfaces are a defining contract for what the use can expect.

Interfaces are important because they separate what a class does from how it does it. The contract defining what a client can expect leaves the developer free to implement it any way they choose, as long as they uphold the contract.

and

An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X".

and

I think the interface-based approach is significantly nicer. You can then mock out your dependencies nicely, and everything is basically less tightly coupled.

What is the point of an interface?

What are interfaces?

Interface + Extension (mixin) vs Base Class

Given that the purpose of interfaces is to define a contract and make your dependencies loosely coupled, doesn't having some methods throw an UnsupportedOperationException kind of defeat the purpose?  It means I can no longer be passed a Set and just use addAll. Rather, I have to know what implementation of Set I was passed, so I can know if I can use addAll or not. That seems pretty worthless to me.

So what's the point of UnsupportedOperationException? Is it just making up for legacy code, and they need to clean up their interfaces? Or does it have a more sensical purpose that I'm missing?

答:
Look at the following interfaces:

Collection

List

Map

Set

These interfaces all declare mutating methods as optional. This is implicitly documenting the fact that the Collections class is able to return implementations of those interfaces that are immutable: that is, those optional mutation operations are guaranteed to fail. However, per the contract in the JavaDoc, all implementations of those interfaces must allow the read operations. This includes the "normal" implementations such as HashSet and LinkedList as well as the immutable wrappers in Collections.

Contrast with the queue interfaces:

Deque

Queue

These interface do not specify any optional operations: a queue, by definition, is designed to offer and poll elements in a FIFO manner. An immutable queue is about as useful as a car without wheels.

One common idea that comes up repeatedly is having an inheritance hierarchy that has both mutable and immutable objects. However, these all have drawbacks. The complexity muddies the waters without actually solving the problem.

A hypothetical Set could have the read operations, and a subinterface MutableSet could have the write operations. Liskov tells us that a MutableSet could then be passed in to anything that needs a Set. At first this sounds okay, but consider a method that expects the underlying set will not be modified while read: it would be possible for two threads to use the same set and violate the invariant of the set not changing. This could cause a problem e.g. if a method reads an element from the set twice and it is there the first time but not the second time.

Set could have no direct implementations, instead having MutableSet and ImmutableSet as subinterfaces which are then used for implementing classes. This has the same issue as above: at some point in the hierarchy, an interface has conflicting invariants. One says "this set must be mutable" and the other says "this set cannot change."

There could be two completely separate hierarchies for mutable and immutable data structures. This adds a ton of extra complexity for what ends up being very little gain. This also has the specific weakness of methods that do not care about mutability (e.g. I just want to iterate a list) must now support two separate interfaces. Since Java is statically typed, this means extra methods to handle both interface hierarchies.

We could have a single interface and allow implementations to throw exceptions if a method is not applicable to it. This is the route Java took, and it makes the most sense. The number of interfaces is kept to a minimum, and there are no mutability invariants because the documented interface makes no guarantees about mutability either way. If an immutability invariant is required, use the wrappers in Collections. If a method does not need to change a collection, simply do not change it. The drawback is a method cannot guarantee a collection will not change in another thread if it is provided a collection from outside, but that is a concern of the calling method (or its calling method) anyway.

Related reading: Why doesn't Java 8 include immutable collections?


答:
It's basically YAGNI.  All the concrete collections in the standard library are mutable, implementing or inheriting the optional operations.  They don't care about general purpose immutable collections and neither do the vast majority of Java developers.  They're not going to create an entire interface hierarchy just for immutable collections, then not include any implementations.

On the other hand, there are a few special-purpose values or "virtual" collections that could be very useful as immutable, such as empty set, and nCopies.  Also, there are third-party immutable collections (such as Scala's), which might want to call existing Java code, so they left the possibility for immutable collections open in the least disruptive way.

Title: UnsupportedOperationException in java collections framework interfaces

Body:
Looking through the Java Collections Framework, I've noticed quite a few of the interfaces have the comment (optional operation). These methods allow implementing classes to through an UnsupportedOperationException if they just don't want to implement that method.

An example of this is the addAll method in the Set Interface.

Now, as stated in this series of questions, interfaces are a defining contract for what the use can expect.

Interfaces are important because they separate what a class does from how it does it. The contract defining what a client can expect leaves the developer free to implement it any way they choose, as long as they uphold the contract.

and

An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X".

and

I think the interface-based approach is significantly nicer. You can then mock out your dependencies nicely, and everything is basically less tightly coupled.

What is the point of an interface?

What are interfaces?

Interface + Extension (mixin) vs Base Class

Given that the purpose of interfaces is to define a contract and make your dependencies loosely coupled, doesn't having some methods throw an UnsupportedOperationException kind of defeat the purpose?  It means I can no longer be passed a Set and just use addAll. Rather, I have to know what implementation of Set I was passed, so I can know if I can use addAll or not. That seems pretty worthless to me.

So what's the point of UnsupportedOperationException? Is it just making up for legacy code, and they need to clean up their interfaces? Or does it have a more sensical purpose that I'm missing?


问:
Building a class that contains built classes
I have some classes I've created that are immutable and follow the builder pattern. I'm now creating a composite class that will include those classes as fields. Should the builder for that composite class call through to the sub-builders and then build them in the outer builder's build() method, or should the composite builder have methods that accept already constructed instances of the contained classes, or should I allow both options?

答:
I'm going to assume your classes are called Composite, Foo, Bar and Baz.

The simplest option is to let CompositeBuilder take pre-built Foos/Bars/Bazs, so you get new CompositeBuilder().setFoo(...).setBar(...).setBaz(...).build(). The big advantage here is that the API to your Composite class is dead simple, both for you and your users. KISS and YAGNI apply here. Plus, you still get the option of subclassing Foo/Bar/Baz, and this might make it easier to change Foo/Bar/Baz themselves since Composite doesn't have to know much about them.

The alternative of having CompositeBuilder provide it's own interface has other potential advantages, assuming that you provide a much smaller, narrower interface than the one you get "for free" from the three subbuilders. That can potentially make Composite much easier to work with, and opens the possibility of someday changing Composite to use Oof/Rab/Zab instead of Foo/Bar/Baz without affecting client code, in case subclassing isn't enough.

I would avoid providing both, unless you're very sure you have a lot of users that want a simplified interface and a lot of other users who need the full power of a raw FooBuilder. Trying to do too many things at once always runs the risk of doing none of them well (and making it hard for anyone to figure out how they're supposed to use Composite).

Which one you should pick depends on a lot of factors you haven't described. How complicated are the three subbuilders? How much customization does a Composite need? Will users of CompositeBuilder already be familiar with the Foo/Bar/BazBuilders? Do they despise the current Foo/Bar/BazBuilder interfaces? Are there separate "consumers" and "producers" of these objects, or are they usually used in the same place where they're built? Would it ever make sense to change the classes that Composite is implemented with? And so on and so forth.


答:
I tend to prefer a builder for each object that accepts fully built sub-objects.

The primary reason is this path provides simplicity of implementation, without loss of flexibility of expression. Also, I find it more readable.

Compare two completely facetious examples:

```<code>CompositeClass.builder()
              .withArgument(some_arg)

              .withSubclass1Argument1(some_arg)
              .withSubclass1Argument2(some_arg)

              .withSubclass2Argument1(some_arg)
              .withSubclass2Argument2(some_arg)
              .build();
</code>```

vs

```<code>CompositeClass.builder()
              .withArgument(some_arg)
              .withSubclass1(Subclass1.builder()
                                      .withArgument1(some_arg)
                                      .withArgument2(some_arg)
                                      .build())
              .withSubclass2(Subclass2.builder()
                                      .withArgument1(some_arg)
                                      .withArgument2(some_arg)
                                      .build())
              .build()
</code>```

It comes down to personal preference, but I find the second easier to read and work with.

Title: Building a class that contains built classes

Body: I have some classes I've created that are immutable and follow the builder pattern. I'm now creating a composite class that will include those classes as fields. Should the builder for that composite class call through to the sub-builders and then build them in the outer builder's build() method, or should the composite builder have methods that accept already constructed instances of the contained classes, or should I allow both options?

Body:
I tend to prefer a builder for each object that accepts fully built sub-objects.

The primary reason is this path provides simplicity of implementation, without loss of flexibility of expression. Also, I find it more readable.

Compare two completely facetious examples:

CompositeClass.builder()
              .withArgument(some_arg)

              .withSubclass1Argument1(some_arg)
              .withSubclass1Argument2(some_arg)

              .withSubclass2Argument1(some_arg)
              .withSubclass2Argument2(some_arg)
              .build();

vs

CompositeClass.builder()
              .withArgument(some_arg)
              .withSubclass1(Subclass1.builder()
                                      .withArgument1(some_arg)
                                      .withArgument2(some_arg)
                                      .build())
              .withSubclass2(Subclass2.builder()
                                      .withArgument1(some_arg)
                                      .withArgument2(some_arg)
                                      .build())
              .build()

It comes down to personal preference, but I find the second easier to read and work with.


答:
An external function can (in C) be declared locally, inside some function, or even some block; e.g.

```<code> void myfunction(int x) {
    extern void exit(int);
    if (x==42)
      exit(23);
</code>```

So you don't need any #include -d header to declare some external function - and later call it -, but that is a lot more convenient. Hence no headers are needed to call any external function, just an extern declaration of it (and before that, any struct, union, typedef, enum ... declarations related to types needed for that external functions).

The example above is using the standard exit function as an example, but you could do something more, e.g. declare a struct and an extern function returning it, like

```<code> if (x>0) {
    struct pair_st { int aa, bb; };
    extern struct pair_st foobar(int, int);
    struct pair_st p = foobar(x+2, x-3);
    exit (p.aa+p.bb);
 }
</code>```

In addition, a C compiler would consider any undeclared (but called) function as returning an int. You should ask your compiler to issue a warning in that case. If using GCC invoke it with a command starting with gcc -Wall -Wextra -g to get all warnings (-Wall), some extra of them (-Wextra), and debugging info (-g). Then use the debugger (gdb).

You should read more about linkers (e.g. Levine's book on Linkers & Loaders). Generally, they don't care about types or signatures, but just about names (therefore, languages with overloading, like C++, are implemented with compilers doing some name mangling).

At last, some systems have dynamic linkers and are able to load plugins at runtime. My Linux system has (as all POSIX systems) dlopen & dlsym, and in my MELT tool I am doing things similar to:

```<code>FILE* fgensrc = fopen("foobar.c", "w");
emit_some_c_code(fgensrc); // a complex function emiting some C code at runtime
fclose (fgensrc);
// now, compile the runtime generated C file foobar.c into a shared object
if (system("gcc -fPIC -Wall -O -shared foobar.c -o ./foobar.so")>0)
   exit(EXIT_FAILURE);
// open the shared object as a plugin
void* dlh = dlopen("./foobar.so", RTLD_NOW|RTLD_GLOBAL);
// declare a signature typedef
typedef int myintsig_t (int, int);
// declare a pointer to a function of that signature
myintsig_t* ptrfun =
// fetch a function pointer by its name at runtime!
   (myintsig_t*) dlsym(dlh,"foobarfun");
if (!ptrfun) { fputs(stderr, dlerror()); exit(EXIT_FAILURE); };
/// call the function thru the pointer!
x = (*ptrfun) (x, x+3);
</code>```

In reality, you should add a lot more of error checks.
All the literal strings above "foobar.c", "foobarfun" .... could be computed at runtime!

A function can be called in C indirectly thru a pointer to function. An implementation could provide functions (like dlsym) able to return pointers to other functions.

So you see that on Linux you could emit some C code at runtime, compile it, then access and invoke a function whose name is only known at runtime in that code....

Plugins and their dynamic loading with dlopen  is not defined by the C language standard but by POSIX. Some other operating systems (e.g. Windows, which I don't know) also have such dynamic loading abilities.

Notice that the C standard does not know about libraries, only about translation units (or compilation units).

Title: In C, how are functions accessible if they're not inline or called by #include?

Body:
I'm looking at code that somehow calls a library but I don't see it calling any of the library's headers at any point.  I've done searches within the code and I don't see anywhere the functions, typedefs or structs getting defined anywhere...yet it compiles and works, and LDD shows it calling the library.  What is it that's inherent to the C language that allows this to work?

Code that references functions/typedefs/structs non-existent elsewhere in code:

```<code>typedef struct pngbuffer_s
{
    byte *buffer;
    png_size_t size, offset;
} pngBuffer_t;
</code>```

Body:
An external function can (in C) be declared locally, inside some function, or even some block; e.g.

 void myfunction(int x) {
    extern void exit(int);
    if (x==42)
      exit(23);

So you don't need any #include -d header to declare some external function - and later call it -, but that is a lot more convenient. Hence no headers are needed to call any external function, just an extern declaration of it (and before that, any struct, union, typedef, enum ... declarations related to types needed for that external functions).

The example above is using the standard exit function as an example, but you could do something more, e.g. declare a struct and an extern function returning it, like

 if (x>0) {
    struct pair_st { int aa, bb; };
    extern struct pair_st foobar(int, int);
    struct pair_st p = foobar(x+2, x-3);
    exit (p.aa+p.bb);
 }

In addition, a C compiler would consider any undeclared (but called) function as returning an int. You should ask your compiler to issue a warning in that case. If using GCC invoke it with a command starting with gcc -Wall -Wextra -g to get all warnings (-Wall), some extra of them (-Wextra), and debugging info (-g). Then use the debugger (gdb).

You should read more about linkers (e.g. Levine's book on Linkers & Loaders). Generally, they don't care about types or signatures, but just about names (therefore, languages with overloading, like C++, are implemented with compilers doing some name mangling).

At last, some systems have dynamic linkers and are able to load plugins at runtime. My Linux system has (as all POSIX systems) dlopen & dlsym, and in my MELT tool I am doing things similar to:

FILE* fgensrc = fopen("foobar.c", "w");
emit_some_c_code(fgensrc); // a complex function emiting some C code at runtime
fclose (fgensrc);
// now, compile the runtime generated C file foobar.c into a shared object
if (system("gcc -fPIC -Wall -O -shared foobar.c -o ./foobar.so")>0)
   exit(EXIT_FAILURE);
// open the shared object as a plugin
void* dlh = dlopen("./foobar.so", RTLD_NOW|RTLD_GLOBAL);
// declare a signature typedef
typedef int myintsig_t (int, int);
// declare a pointer to a function of that signature
myintsig_t* ptrfun =
// fetch a function pointer by its name at runtime!
   (myintsig_t*) dlsym(dlh,"foobarfun");
if (!ptrfun) { fputs(stderr, dlerror()); exit(EXIT_FAILURE); };
/// call the function thru the pointer!
x = (*ptrfun) (x, x+3);

In reality, you should add a lot more of error checks.
All the literal strings above "foobar.c", "foobarfun" .... could be computed at runtime!

A function can be called in C indirectly thru a pointer to function. An implementation could provide functions (like dlsym) able to return pointers to other functions.

So you see that on Linux you could emit some C code at runtime, compile it, then access and invoke a function whose name is only known at runtime in that code....

Plugins and their dynamic loading with dlopen  is not defined by the C language standard but by POSIX. Some other operating systems (e.g. Windows, which I don't know) also have such dynamic loading abilities.

Notice that the C standard does not know about libraries, only about translation units (or compilation units).


问:
How to suspend open source support?
I'm the only active maintainer for an open source project, which receives support requests on various channels (Twitter, email, GitHub) almost daily. I'll be on vacation for the next three months, where I'll have very limited time to respond, let alone accept pull requests or resolve issues. What can I do to prevent disappointing people that put in time to ask a good question or write a proper bug report?</p>

答: There are basically two ways to handle this.  Either hand it off to someone else, (which apparently is not an option here,) or simply post something on the project site and on "various channels" that you'll be unavailable for a while.  There really isn't much you can do beyond that.</p>

Title: How to suspend open source support?


问:
Why does Apache have two separate tools for build and dependency management?
Apache has two separate tools:

Apache Maven

Apache Ant + Apache Ivy

They seem to both fill the same niche. I have two questions:

What are the highlights of the main differences between the two tools?

I'm sure a really long article could be written on the differences between the two, I am not looking for that much detail, nor am I looking for a subjective argument for choosing one over the other.

History of programming - how did it happen that Apache evolved to create two completely separate sets of tools that are ultimately so similar in purpose?

答:
What are the highlights of the main differences between the two tools?

Project structure

Maven prefers a specific project structure: one must commit to doing things The Maven Way. Maven comes with common build steps already configured in a root pom.xml that is normally inherited by all other project pom.xmls.

Ant+Ivy is more open-ended: while it can do a lot, there are only a few basic requirements in terms of project structure or script usage. There are no predetermined build tasks, goals, or processes. Each build.xml is a clean slate (unless including another script, of course).

Orientation

Maven is goal oriented. You do not say "execute this build target" you ask it to "build" or "deploy" and Maven does whatever it needs to do to get there: you say what you want to do.

Ant+Ivy is task oriented. Each task is implementation-defined and custom. You tell it how to do what you want.

Dependency Management

Maven is best-known for automatically handling dependencies. It will download the correct versions while building without any user interaction as long as the repository URLs are properly configured ahead of time.

Ant has no dependency management except for "Java Classpath." Ivy adds dependency management that is a little more tedious than Maven but still automated. The key here is you can choose no dependency management (e.g. "jars included in my distro or checked into source control") or you can outsource it via Ivy. That choice means more flexibility to meet project needs.

Ease of Use

Maven is (in theory) easy to use. Any developer can pick up a Maven project and immediately know where all of the project resources are located and what they are for: this is due to the first point about Maven having a specific way of doing things.

Ant+Ivy may have a steeper learning curve because each project can be different. Different projects may have different ways of accomplishing the same goals.

Extensibility

Maven allows writing plugins and altering its build process. However, it comes out of the box with a root pom.xml that pushes developers toward its predetermined build processes. New goals or build steps require careful thought and extra effort to inject into the build process.

Ant+Ivy also allows writing plugins and new tasks: doing so is quite easy and one can integrate a new task with minimal effort. There are no predetermined goals or targets to shuffle around or to integrate one's new task into.

How did it happen that Apache evolved to create two completely separate sets of tools that are ultimately so similar in purpose?

The first thing to understand is the Apache project is nothing more than an umbrella under which separate, independent projects operate. Different teams work on different projects. While individual developers may work on multiple projects, there is not some overall roadmap that incorporates Ant, Ivy, and Maven.

Ant came first. It was designed to be a Java equivalent of Make. While Make can build Java projects, it is tedious: Make existed to compile a bunch of compilation units separately then link them. The Java way is javac compiles everything in one go, and what we call "linking" really occurs in the guts of the JVM at runtime. Make was not the right tool for the job: a Makefile for Java is basically one or two targets (javac, jar).

Ant added a little bit of structure on top of Make, but did not fundamentally alter the process.

After a while the community came to realize that hunting down jar files was not fun. Furthermore, there was no standard way to compose projects. With no consistency, Java development was a mess. Maven was designed to solve these problems: it would bring a common project structure and automate the hunting down of jar files.

However, Ant was still really useful. Some projects just lend themselves more to the ad-hoc nature of Ant's processes. Some projects are not compiling code. Some projects were old and it was unlikely anyone would "upgrade" them to Maven.

Along comes Ivy: it adds dependency management to Ant, giving projects the best of both worlds. You can keep your legacy scripts, or you highly customized environment, but gain Maven's most important feature: dependency management.


问:
Right-aligning code
I recently was looking for a CSS solution to vertically-align elements, and I found one here.

One thing that I thought was nice was the right-justified code; example:

```<code>.vertical-center {
    // ... other stuff ...

           -webkit-box-pack : center;
              -moz-box-pack : center;
              -ms-flex-pack : center;
    -webkit-justify-content : center;
            justify-content : center;
}
</code>```

It looks nice, and is a bit easier to read (in my opinion). However, I prefer tabs, and this kind of formatting requires spaces. That's not the main issue though.

The problem is that it seems to me that code like this becomes unmaintainable because one becomes focused on 'beautifying' the code instead of doing something more productive.

How can this be reconciled, so that code is both easy to read and to write?

答:
This sort of thing can always be done with an IDE. I am not familiar with an IDE that supports this exact formatting, but I know that most modern IDEs have highly customizable settings for formatting code.

As a Java programmer using Eclipse, I have it set so that I can type Ctrl+A(select all) Ctrl+Shift+F(code-format) and it will prettify all my Java code using the settings I've set for my project.

In short, it really doesn't add to your development time, with a proper IDE, and if it makes the code easier to read, go ahead and do it! The worst case would be that you have to write your own extension for your IDE for this particular format, which could be a little bit of a pain.

Title: Right-aligning code


问:
Reducing a sequence of array modification operations (insert, sort, replace, remove)
Given a plain array of values, e.g.

```<code>["Apple", "Orange", "Banana", "Strawberry"]
</code>```

and a list of operations from the set of [insert, delete, sort and replace], e.g.

```<code>[
  {cmd: "insert", index: 2, entries: ["Cherry", "Kiwi"]},
  {cmd: "delete", indices: [3]},
  {cmd: "sort", newOrder: [3,1,2,0,4]},
  {cmd: "insert", index: 3, entries: ["Peach"]},
  {cmd: "replace", index: 3, newEntry: "Raspberry"}
]
</code>```

which should result in the array

```<code>["Banana", "Orange", "Cherry", "Raspberry", "Apple", "Strawberry"]
</code>```

How can I, with relatively little effort, transform my sequence of operations into something less redundant? E.g.

```<code>[
  {cmd: "sort", newOrder: [2,1,0,3]},
  {cmd: "insert", index: 2, entries: ["Cherry", "Raspberry"]}
]
</code>```

Note that deleting an entry and then inserting an identical one is considered equivalent to adding a completely new entry, whereas inserting a new entry and later deleting cancels out. Edits/replacements/renames of entries need to be kept track of, but they don't combine with any of the other operations.

Question:

This seems like something that would come up in the context of database query optimization, but I have no idea what to google for. I'm ultimately looking for an algorithm (preferably a JS implementation) that automates this kind of thing for me, if only in a naïve/greedy fashion (it doesn't have to exhaustively search for the best reduction, if it can't be done in polynomial time).

Background:

This came up while working on a web app in which the user can edit a list of entries, accept and submit those edits, and they then trigger a reshuffling of a set of corresponding arrays on the server. That means that I have to capture how the elements move around in the array, not just what the array looks like after all the changes are done. (I need to keep track of the operations for undo/redo functionality anyway.) Since the amount of data involved can be quite large, combining those operations before sending them would translate to shorter uploading times and fewer database writes server-side. All of this is purely theoretical at this point and may well amount to premature optimization, but I found it an interesting problem and would love some input.

答:
The most straightforward way would be to track some metadata along with the array, so you end up with a data structure something like this:

```<code>[{name: "Banana", originalOrder: 2},
 {name: "Orange", originalOrder: 1, deleted: true},
 {name: "Cherry", new: true},
 {name: "Raspberry", new: true},
 {name: "Apple", originalOrder: 0},
 {name: "Strawberry", originalOrder: 3}]
</code>```

Then it's all relatively simple linear operations to find the new order, create a list of deletions, and create a list of insertions.

Body:
The most straightforward way would be to track some metadata along with the array, so you end up with a data structure something like this:

[{name: "Banana", originalOrder: 2},
 {name: "Orange", originalOrder: 1, deleted: true},
 {name: "Cherry", new: true},
 {name: "Raspberry", new: true},
 {name: "Apple", originalOrder: 0},
 {name: "Strawberry", originalOrder: 3}]

Then it's all relatively simple linear operations to find the new order, create a list of deletions, and create a list of insertions.


问:
Partial Update of Database Table
I have a database table with numerous fields including "category". The source of this table is an xml file which the system receiving occasionally. Each xml file contains data for one category. The table needs to be updated with the new category data from the xml file. The xml file includes all data for that category, not just the changes.

I see two possible ways of handling this:

First deleting all rows from the table where category = categoryID, and then doing inserts based on all the xml data. Obviously the deletion and insertion operations would be contained within a transaction.

For each record in the xml, first do a select to test if that record exists. If it does exist, update the data with that from the xml. If it doesn't exists, insert it.

Obviously, the second approach avoids deleting the data first but involves many more db queries although this could be mitigated by doing an initial select to a hash table, and just querying the hash. The big downside to the second approach is how to handle deletions, i.e. records that no longer appear in the xml and should be removed from the table.

What is the best practice for handling this kind of operation?

Thanks.

答:
I agree with Snowman and think you should do all the queries. Along with performance being negligible, you can gain some insights about the data changes that may benefit you and/or users:

New Categories

Removed Categories

Categories that have changed.

Someone is eventually going to ask what happened. "We got a new file," won't be enough.

Title: Partial Update of Database Table


答:
I'd try something like symbolic computing where we run the computation over an abstraction of all possible starting states, the goal of this symbolic execution is to produce an abstraction of the ending state, which is then reflective of the computations performed by the set of operations to be optimized.

(Because we use an abstraction of all possible starting states, we can perform the transformation (by symbolic execution) of input steps to their effect (as abstract output state) without involving the real database.)

The abstract state that you can compute over will store nodes of several kinds.  First constant or known nodes, having fixed index and known value, like 2:Cherry, which is like what the real list can store, and second, unknown values over known ranges (e.g.I'll write ?0-1 to mean unknown value from positions 0 thru 1 in the original input), and unknown values over only partially known range (e.g. I'll write ?0-N where N is the length of the input list).

So, the initial abstract state is a list of length N of unknown values, which I'll represent as [ ?0-N ], an abstract list of one node that says it has the original values (unknown) from the list positions 0 thru N.

After the insertion of the first step, our abstract list will have four nodes.  One to represent the range 0-1, one each for positions 2 and 3 (inserted), and one for the remaining positions.  The abstract list now looks like [ ?0-1, 2:Cherry, 3:Kiwi, ?2-N ] where ?2-N means the original value of 2 thru the original values to the length of the list.

After the deletion, we remove element at position 3 in the (current) abstract list, leaving us with [ ?0-1, 2:Cherry, ?2-N ].  And so on...

The sort operates on the immediately above and leaves us with:
[ ?2, ?1, 2:Cherry, ?0, ?3, ?4-N ].

The next insert changes the abstract state to: [ ?2, ?1, 2:Cherry, 3:Peach, ?0, ?3, ?4-N ].
And the replace results in: [ ?2, ?1, 2:Cherry, 3:Raspberry, ?0, ?3, ?4-N ].

That end result for this symbolic computation over the abstract state will tell us the resulting command to execute to get that effect on an arbitrary input list, and if you like can be teased apart into sorts, deletes, and inserts; However we might be better off if we could interpret the abstract result state as a single command directly by adding a new bulk change command that can do several kinds of operations in one go (e.g. cmd:change-list substitute:[ ?2, ?1, Cherry, Raspberry, ?0, ?3, ?4-N ])

Title: Reducing a sequence of array modification operations (insert, sort, replace, remove)

Body:
Given a plain array of values, e.g.

```<code>["Apple", "Orange", "Banana", "Strawberry"]
</code>```

and a list of operations from the set of [insert, delete, sort and replace], e.g.

```<code>[
  {cmd: "insert", index: 2, entries: ["Cherry", "Kiwi"]},
  {cmd: "delete", indices: [3]},
  {cmd: "sort", newOrder: [3,1,2,0,4]},
  {cmd: "insert", index: 3, entries: ["Peach"]},
  {cmd: "replace", index: 3, newEntry: "Raspberry"}
]
</code>```

which should result in the array

```<code>["Banana", "Orange", "Cherry", "Raspberry", "Apple", "Strawberry"]
</code>```

How can I, with relatively little effort, transform my sequence of operations into something less redundant? E.g.

```<code>[
  {cmd: "sort", newOrder: [2,1,0,3]},
  {cmd: "insert", index: 2, entries: ["Cherry", "Raspberry"]}
]
</code>```

Note that deleting an entry and then inserting an identical one is considered equivalent to adding a completely new entry, whereas inserting a new entry and later deleting cancels out. Edits/replacements/renames of entries need to be kept track of, but they don't combine with any of the other operations.

Question:

This seems like something that would come up in the context of database query optimization, but I have no idea what to google for. I'm ultimately looking for an algorithm (preferably a JS implementation) that automates this kind of thing for me, if only in a naïve/greedy fashion (it doesn't have to exhaustively search for the best reduction, if it can't be done in polynomial time).

Background:

This came up while working on a web app in which the user can edit a list of entries, accept and submit those edits, and they then trigger a reshuffling of a set of corresponding arrays on the server. That means that I have to capture how the elements move around in the array, not just what the array looks like after all the changes are done. (I need to keep track of the operations for undo/redo functionality anyway.) Since the amount of data involved can be quite large, combining those operations before sending them would translate to shorter uploading times and fewer database writes server-side. All of this is purely theoretical at this point and may well amount to premature optimization, but I found it an interesting problem and would love some input.


问:
Do I have to distribute my commercial source code that links GPL software if I only use this commercial software to provide a reporting service?
At my company we created proprietary software that we use only internally - we do not distribute this software - to generate reports from client data. We sell these reports to our clients, not the software.

If we were to link to GPL licensed software from our software, would will still need to (upon request) provide our proprietary source code?

I understand that if we distributed our proprietary software itself, the answer would be yes. And I understand that if we used the proprietary software only for internal purposes, the answer is no (e.g., see discussion here). But if we only use the proprietary software internally, in order to generate a report product that we do sell (distribute) to customers, then what is the answer? This link seems to suggest probably not, but what if the GPL software creates a particular image that is displayed on one page in a many-page report?

Thanks in advance for some clarity on this. Legalese is so hard for me to understand, but if you could also point me to the particular sections of the GPLv3 that make this clear, I'd appreciate it.

答:
For the regular GPL, the answer is no. Quoth the FSF FAQ:

Q: Is there some way that I can GPL the output people get from use of
  my program? For example, if my program is used to develop hardware
  designs, can I require that these designs must be free?

A: In general this is legally impossible; copyright law does not give
  you any say in the use of the output people make from their data using
  your program. If the user uses your program to enter or convert his
  own data, the copyright on the output belongs to him, not you. More
  generally, when a program translates its input into some other form,
  the copyright status of the output inherits that of the input it was
  generated from.

In this case, you are the "user" of the GPL'd program, so the output is all yours.

It's worth mentioning that if we were talking about the AGPL, and your clients were "interacting with [the software] remotely through a computer network", then the answer would be very different. But it sounds like neither of those conditions apply to your case.


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

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

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

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

答: Redundant code is very very evil.</p>

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?

Body: Redundant code is very very evil.


问:
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.

答:
In your example I see no benefit, but other languages (like Ceylon) use union types in useful ways. Imagine doing something like this (C#)

```<code>int Length<A> (String | List<A> obj) {...}
</code>```

While this example isn't very meaningful since String implements IEnumerable, the idea behind this is that you can receive a parameter which can be one various type, use the fields/properties/methods those types have in common naturally, and use switch/case when type dependent behavior is needed.

In F# I guess you could create some helper types to accomplish little things like this. I prefer the Ceylon way: Polymorphism + (mainly anonymous) Union Types.

Union Types can help a lot for correctness if you assume that null is the only instance of type Null, then if you want to declare that something can be null you should use the type T | Null or its abbreviation T?.

Body:
In your example I see no benefit, but other languages (like Ceylon) use union types in useful ways. Imagine doing something like this (C#)

int Length<A> (String | List<A> obj) {...}

While this example isn't very meaningful since String implements IEnumerable, the idea behind this is that you can receive a parameter which can be one various type, use the fields/properties/methods those types have in common naturally, and use switch/case when type dependent behavior is needed.

In F# I guess you could create some helper types to accomplish little things like this. I prefer the Ceylon way: Polymorphism + (mainly anonymous) Union Types.

Union Types can help a lot for correctness if you assume that null is the only instance of type Null, then if you want to declare that something can be null you should use the type T | Null or its abbreviation T?.


问:
workflow tips & tricks for managing incomplete and not-yet functioning code?
I do web app development and bash scripting and I usually work on several projects at once in different contexts and languages and often return to a project after a few months absence.

When I return to a project there are always fragments of code that are incomplete and I have trouble "re-familiarising" myself with what I was doing and what I was trying to acheive.

I use version control and can look at the history, but that only gives a backward look at what happened in the past.

Regarding outright breaking code

I use version control "topic" branches to isolate any code that outright breaks functionality, Im more struggling with trying to understand the  state of affairs of the little bits of incomplete, but "non-breaking" work.

Does anyone have any suggestions on how I might manage these items in a "forward looking" way? , possibly along the lines of

TODO's

issues in github/bitbucket

commenting out code

have the code run an alert -  in the app - to say I need to be finished

write unit test definitions which explains what you are trying to achieve - even if the unit test wont be written till later

etc

答:
The best way to manage such incomplete changes/additions is to avoid having them in the first place. Try to make your features small enough that you can completely implement them in the time span that you are typically able to work on a single project.

If you can typically work on a project for 4 or 5 hours, spread over a few days, before life kicks in or you have to switch to another project, then you should try to size your work packages to be no more than those 4 to 5 hours.

For the longer term plans you have with a project (all the work you want to do on it, but haven't got around to yet), you can use several methods ranging from a simple bullet-list on paper to a full-fledged issue tracking system. There you should just use what works best for you personally.


问:
How to break mental model of objects
I've been working with OOP for a while now, but in each large project that I find myself starting, I seem to run into the same problem; where does the responsibility reside.

Like many who use OOP on a regular basis, it becomes natural to start breaking things into nouns, verbs, adjectives, etc. Recently I read a post about whether or not an object can, or should, contain any state information, or if it should be only state information. During this post, I saw a response that mentioned Martin Fowler's Mark IV Coffee Maker. Everybody seemed to agree that breaking things out in that way was indicative of a good design. The problem I have is that I don't see it that way. To me, it seems backwards in some parts. I haven't been doing this for nearly as long as some of you have, so I'd like to ask if there's any what I can break this habit, or what I can do to change it.

One example we can consider is a light bulb. Let's say there are two use-cases, where a Person wants to turn on the light, and where a Person wants to turn off the light. This could be reduced to one use-case, where they want to toggle the light, potentially.

If I understand that example, the responsibility of Light turning on or off should be the responsibility of the Light object, with something like

```<code>public interface Light {
    void turnOn();
    void turnOff();
    void toggle();
}
</code>```

However, when I think about this situation, a Light cannot turn itself off, or turn itself on. This happens in response to some sort of event, or action. My kitchen light usually doesn't turn on or off by itself. It's not intelligent. A Person or Switch can turn a light on or off; but a Light cannot. Its state is entirely determined by something else. So where should the responsibility reside? All of the projects I have been a part of, that I have ended up quitting, have boiled down to this question. What sort of tools, mental or physical, can I use to write more OO code?

Note: Most of the project I have worked on have been in Java; it is my most comfortable language. This question is more language-agnostic though.

答:
The responsibility for getting something done should reside with the object that models the state that changes when you do it.

You're right that a lightbulb doesn't turn itself off. However, that's not what calling an object method means. The accepted mental model is sending a message to an object. In the real world you do this by flipping its associated switch. In the programming world, the caller invokes an object method with parameters. In both scenarios the bulb is passive and others act on it.

Therefore, bulb.toggle() is the preferred way of notating this action. Neither the person pressing the switch nor the switch itself are mentioned because what you care about is the state of the bulb (the room gets dark), not the state of the switch (the contact is without current) or the state of the person (slightly more tired from the effort?). The state of the person would only be relevant if you wrote a fitness app tracking the energy expended by the user. The state of the switch... actually, I can't think of a plausible scenario where you would want to model that.

Title: How to break mental model of objects


问:
Will TDD really save bug fixing time for WPF/MVVM
I'm looking for an update .net 4.5 WPF+MVVM+TDD tutorial for my team.

I have found only one good tutorial

https://deltaengine.fogbugz.com/?W199

My goal is to learn Test Driven Development using WPF and MVVM (we know WPF and MVVM and also use Nunit for unit testing and coded UI)

However I think we can save a lot of time with practicing TDD. Our system contains WPF/MVVM/C# with c++/CLI and C++.

Do you think TDD will reduce the time being spent of bug fixing ?

答:
The point of TDD from a business perspective is really not so much reducing bug-fixing time. You do reduce the maintenance effort, but you spend more time fixing defects while you write the code in the first place, because you never get things entirely correct on the first try (if you could, you wouldn't testing at all). Sometimes one effect predominates, sometimes the other.

However, TDD is still worthwhile because shifting effort upfront makes your process cheaper. The earlier you catch an error, the cheaper it is to fix. It you catch it while it's in your head, you haven't wasted time writing it. If you catch it before you check in, you don't waste time reverting the commit. If you catch it before QA gets their hands on it, you haven't wasted their time. (If you don't catch it until it's live with a customer, fixing it becomes horrifically expensive because you've wasted their time, the time of the support staff, and your own time that could have been used for improving the code base.)

In my opinion, test-driven workflows don't so much reduce errors as shift the occurrence of errors from more expensive to less expensive places in the development process. And that has enough business value to justify turning your way of doing things around.


问:
How can I transition to a job using the Microsoft stack?
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?

答:
If you want to move in that direction you want to focus on building you experience with the technologies. You can do this in a number of ways. First is to work on your own projects using the Microsoft products. Fortunately they have at least provided a number of free tools like Visual Studio express, so you can at least get your feet wet. If you do not have anything in mind that you want to work on, just find some books and read and go through any exercises or examples that they provide. You can also look to see if there are any .NET user groups in you area and start attending those and networking. If there are no user groups, maybe look for conferences near you. Thirdly see if you can find a company that makes use of multiple technologies where you can use your existing skills, but have an opportunity to be exposed to other technologies and gain some additional experience on the job.
Many of the skills you have learned will still apply regardless of the technology and language you are using. So also continue to focus on continuing to develop those skills.</p>


问:
Is there a practical way to manage a physical task board if one or more scrum team members works remotely?
I've convinced a few colleagues to try scrum with me, but one of them works remotely. We'd like to try using a physical task board.

I think we might be able to pull it off by snapping a photo and sending it to him every time the board is updated, and when he wants to update any of his tasks at the end of the day, he can just ask me to do it for him. It seems simple enough, but I'm not sure if we would be better off just using an online task board like Trello.

We're also considering managing a physical board and a Trello board but would like to avoid dual maintenance.

Has anyone implemented scrum with a physical task board shared with remote team members? If so, what worked and what didn't work?

答:
I am currently working in a Scrum team that consists of a mixture of on-site and off-site developers. The lessons I have learnt so far here are:

You really need to use a digital board. We started out using a physical board, using a webcam to show the board to the off-site team members. The biggest problem here is that you can't get a good overview of the board. Either you see a large portion of the board but can't read the cards, or you can read the cards but not see where they are on the board.

Also, the off-site developers can't easily refer to the board to see what the next task is that they can pick up.

With a digital board, none of those problems exist. During the daily standup, we use a conference call with a shared desktop showing the board to ensure that we are all looking at the same part of the board. This is mostly because our board doesn't fit on one screen (it has a scrollbar).

Make sure that every once in a while, all team members are co-located. We found out that over time the product vision and what was meant by the different stories started to drift apart between the on-site and off-site team members. This seems to result mostly from the communication barrier that arises when you only have phone/e-mail/IM to communicate.

We resolved this by arranging that every few weeks the entire team comes together at one location to re-align themselves. We also try to schedule the more intensive design discussions for those times.


问:
Website form testing
My boss has three websites and each of those websites have forms on them that people can sign up for nightclubs.

He asked me to look up usability tests, however, I don't think that's what hes actually looking for. In fact, he wants the forms tested frequently (for instance once per day) to make sure they are working properly.

Is usability testing the right tool for that? If not, what is the right way to do it?

答:
You're right, usability testing has a very different purpose. It consists of asking a user to manipulate a part of your product, and look at the way the user tries to achieve something. The goal is to ensure that user experience of your product is right and if there are things which could be improved to make the product easier, more intuitive or faster to use.

What are you looking for is regression testing. Regression testing is about checking whether things which worked before still work after the code was changed. Smoke tests, functional tests, unit tests or system tests are all part of regression testing.

Depending of what are you precisely testing, the type of tests—and the tools you will use—will differ. For instance, a form on a website can be tested in several ways:

You may test the underlying code using unit tests. Unit tests are short pieces of code which ensure a very short piece of code in your code base (usually a method, although sometimes it might be a whole class) works as expected.

For example, you may have a method which checks that the user entered an e-mail address which looks valid, and use a bunch of unit tests which call this method with e-mail addresses you know to be valid or invalid and check whether the result of the method matches the expectation.

You may also test whether the form itself can be submitted, or that the web app returns an error (such as HTTP 403) if the form contains invalid entries. This is done with system tests and will consist of doing a POST request with specific data, and compare the resulting HTTP status code. Such test, when sending valid input, may even query the database to check that the associated record was created successfully.

You may also test whether the HTML form itself works as expected (for instance, if you inadvertently change the action attribute of the form, it won't work any longer). This is the domain of system and functional testing, with tools such as Selenium which may help you to automate the tests.

Finally, you may need to ensure that the form is showing exactly as it was shown before the latest changes, that is you have a pixel perfect match of the page. For example, adding two pixels to a padding will shift the entire form, eventually breaking the layout.

Since such changes are often barely noticeable when simply looking at the page, you can use pdiff to check for visual differences.

Those four modes of testing ensure that you have a high probability of finding regressions. This being said, there are two aspects which are extremely important if you want regression testing to be effective:

Every test should be automated. Always. No exceptions. You don't have to run tests by hand, by filling the form fields, clicking on buttons and checking whether the result is the same as required by the test. Machines are much better than us at repetitive tasks; they do it in milliseconds instead of hours, and they don't do mistakes.

Tests should run as frequently as possible. Once per day, as you suggested, might be acceptable for some projects, but why can't you do better and run all those tests after every commit? Running tests more often ensures that you find regressions sooner, when you still remember what you're changing right now. If you changed a class and five minutes later, your build server notifies you about a regression, you'll probably find the bug faster than if you receive the notification the next morning, after spending six hours doing dozens of other changes.

Title: Website form testing


问:
Can I make my constructors less repetitive?
I'm extending a class with 10 different constructors.  The new subclass, SpecialImage, is used like this:

```<code>SpecialImage specialImage = new SpecialImage(..);

// Leverage the Rotate() method of superclass Image, which
// returns a new rotated image.
// Notice the type is still SpecialImage.
SpecialImage rotated = specialImage.Rotate(...);
</code>```

SpecialImage implements 5 of the constructors, each of which takes the same additional parameters, Thing stuff and int range:

```<code>public class SpecialImage<TDepth> : Image<Gray, TDepth>
    where TDepth : new()
{

    Thing _stuff;
    int _range;

    public SpecialImage(Thing stuff, int range) : base()
    {
        InitParams(stuff, range)
    }

    public SpecialImage(Thing stuff, int range, Size size) : base(size)
    {
        InitParams(stuff, range)
    }

    public SpecialImage(Thing stuff, int range, int width, int height) : base(width, height)
    {
        InitParams(stuff, range)
    }

    public SpecialImage(Thing stuff, int range, string filename) : base(filename)
    {
        InitParams(stuff, range)
    }

    public SpecialImage(Thing stuff, int range, TDepth[,,] data) : base(data)
    {
        InitParams(stuff, range)
    }

    private void InitParams(Thing stuff, int range)
    {
        _stuff = stuff;
        _range = range;
    }
}
</code>```

This is a tad repetitive, which is only really a problem in the face of maintenance.  Every time the construction requirements of SpecialImage change, I have 5 constructors to change.

I sure feel like I should be repeating myself less, but I don't know how to remove this type of redundancy.  Is it possible to make this less redundant?

答:
You could use composition as lxrec suggested and then retrieve the delegate when you actually need an Image instance. That might be problematic if you'd like to just use SpecialImage wherever you'd previously be using an Image.

Other than that, can't really see a better solution. The only other suggestion I have is to use named factory methods in lieu of constructors, but that's just for readability.


问:
My coworker commits and pushes without testing
When my coworker thinks that there is no need for a test on his PC, he makes changes, commits and then pushes. Then he tests on the production server and realizes that he made a mistake. It happens once in a week. Now I see that he made 3 commits and and pushes with deployment to the production server within 5 minutes.

I told him few times that this is not the way how good work is done. I don't want to be rude to him again and he is in the same status with me in the company and he has worked more than me here.

I want this behavior to be punished in some way or make it unpleasant as much as possible.

Before I started, the company was deploying using antique methods, such as FTP, and there was no version control.

I forced them/us to use Git, Bitbucket, Dploy.io, and HipChat. The deployment is not automatic, someone has to login to dply.io and press the deploy button.

Now, how can I force them to not test on the production server? Something like HipChat bot can sense that there is repeated edits on the same line and send a notice to the programmer.

答:
You need a proper Quality Assurance (QA) process.

In a professional software development team, you don't push from development right to production. You have at least three separate environments: development, staging and production.

When you think that you got something working in your development environment, you push to staging first, where each commit is tested by the QA team, and only if that test is successful, it gets pushed to production. Ideally, development, testing and pushing to production is done by separate people. This can be ensured by configuring your build automation system in a way that developers can only deploy from development to staging and that the QA team can only deploy from staging to production.

When you can't persuade management to hire someone to do your QA, then maybe one of you can play that role for the other. I never worked with diploy.io, but some build automation systems can be configured in a way that a user can deploy both from development to staging and from staging to production, but not do both for the same build, so a second person is always required (but make sure you have some backup people for times when one of you is absent).

Another option is to have your support staff do the QA. This might seem like additional work for them, but it also makes sure that they are aware of any changes to the application which can safe them some work in the long run.


答:
You could use the Builder pattern.

Don't have 10 constructors in Image, have only one which takes all possible parameters. But don't call this constructor from your actual code. Call it from a separate Builder class.

A Builder is a separate class which is initialized with the default values, offers several setters to change these values and a build() method to create a new object with its current values.

Your code to create a new image would then look like this:

```<code>ImageBuilder builder = new ImageBuilder();
builder.setStuff(stuff);
builder.setRange(range);
builder.setSize(size); // alternative overload: builder.setSize(width, height);
builder.setFilename(filename);
Image image = builder.build();
</code>```

Your SpecialImageBuilder would inherit from ImageBuilder. When Image and SpecialImage have the same properties, then likely the only method you need to override is build.

By the way, an elegant trick you can do with builders is to have each setter return this. This is called "fluent interface" and allows you to write code like this:

```<code>Image image = new ImageBuilder()
                  .setStuff(stuff)
                  .setRange(range)
                  .setSize(size)
                  .setFilename(filename)
                  .build();
</code>```

Title: Can I make my constructors less repetitive?

Body:
I'm extending a class with 10 different constructors.  The new subclass, SpecialImage, is used like this:

```<code>SpecialImage specialImage = new SpecialImage(..);

// Leverage the Rotate() method of superclass Image, which
// returns a new rotated image.
// Notice the type is still SpecialImage.
SpecialImage rotated = specialImage.Rotate(...);
</code>```

SpecialImage implements 5 of the constructors, each of which takes the same additional parameters, Thing stuff and int range:

```<code>public class SpecialImage<TDepth> : Image<Gray, TDepth>
    where TDepth : new()
{

    Thing _stuff;
    int _range;

    public SpecialImage(Thing stuff, int range) : base()
    {
        InitParams(stuff, range)
    }

    public SpecialImage(Thing stuff, int range, Size size) : base(size)
    {
        InitParams(stuff, range)
    }

    public SpecialImage(Thing stuff, int range, int width, int height) : base(width, height)
    {
        InitParams(stuff, range)
    }

    public SpecialImage(Thing stuff, int range, string filename) : base(filename)
    {
        InitParams(stuff, range)
    }

    public SpecialImage(Thing stuff, int range, TDepth[,,] data) : base(data)
    {
        InitParams(stuff, range)
    }

    private void InitParams(Thing stuff, int range)
    {
        _stuff = stuff;
        _range = range;
    }
}
</code>```

This is a tad repetitive, which is only really a problem in the face of maintenance.  Every time the construction requirements of SpecialImage change, I have 5 constructors to change.

I sure feel like I should be repeating myself less, but I don't know how to remove this type of redundancy.  Is it possible to make this less redundant?

Body:
You could use the Builder pattern.

Don't have 10 constructors in Image, have only one which takes all possible parameters. But don't call this constructor from your actual code. Call it from a separate Builder class.

A Builder is a separate class which is initialized with the default values, offers several setters to change these values and a build() method to create a new object with its current values.

Your code to create a new image would then look like this:

ImageBuilder builder = new ImageBuilder();
builder.setStuff(stuff);
builder.setRange(range);
builder.setSize(size); // alternative overload: builder.setSize(width, height);
builder.setFilename(filename);
Image image = builder.build();

Your SpecialImageBuilder would inherit from ImageBuilder. When Image and SpecialImage have the same properties, then likely the only method you need to override is build.

By the way, an elegant trick you can do with builders is to have each setter return this. This is called "fluent interface" and allows you to write code like this:

Image image = new ImageBuilder()
                  .setStuff(stuff)
                  .setRange(range)
                  .setSize(size)
                  .setFilename(filename)
                  .build();


答:
You will probably want to get a dev server, and preferably a staging environment too. Nobody should ever be pushing from local to production except for their own personal website. Your deploy process should only support dev->staging->prod. You probably want someone responsible for signing off new releases - depending on the organisation, this can be a project lead, a dedicated QA or a duty that rotates each week (with a tangible reminder e.g. only the person with the fluffy toy that week gets to push). However, discuss it with your team first to get buy-in (see below).

I want this behavior to be punished in some way or make it unpleasant as much as possible.

You could have your test suite (you've got one of those, right?) include a check that determines if you are on a production server and, if it does, sends everyone in the office an email saying Looks like $username is testing on prod, watch out. Perhaps publicly shaming your colleague would be unpleasant. Or your could create technical restrictions like IP-banning your team from looking at prod (which you can lift but you have to justify).

I don't recommend it, though, you would look like the problem, not the person who is testing on prod and you could make yourself very unpopular with the people in the team who don't care.

Surely what you really want is not for this behaviour to be punished but for it to stop?

I forced them/us to use [...]

It's great that you are advocating workflow improvements, but it sounds like either you don't think much of your colleagues and/or that you don't have their full support. This is likely to result in colleagues half-heatedly interacting with the workflow, doing the minimum needed to get code onto production and not really following the spirit of the workflow, which is going to mean more time spent clearing up. And when you're spending more and more time clearing up the results of inadequate interaction with workflow (because nobody else cares, right?) everyone else will be questioning the workflow itself.

So start with a conversation.

Find out why it's happening (is your colleague's machine not as good for testing? Is your colleague uncertain with feature branches or stuck in an svn mindset where commit and push are the same?), explain why it's a problem for you that untested code goes on dev/staging/prod, and see if you can do something to change why it happens (your colleague will more likely do what you want if you've just made it nicer to test locally than if you've just berated them).

If you can't resolve it and it genuinely comes down to a difference of opinion, schedule a teamwide discussion in your next retrospective meeting, see what your colleagues do and think. Make your case, but listen to the consensus. Maybe your team says it's ok not to test textual fixes locally, and you just have a rule that no big features go onto dev untested. Write down in the meeting and read out what you collectively decide about what is allowed on each of the environments. Set a date in a couple of months to review it, maybe at a retrospective.

Title: My coworker commits and pushes without testing

Body:
When my coworker thinks that there is no need for a test on his PC, he makes changes, commits and then pushes. Then he tests on the production server and realizes that he made a mistake. It happens once in a week. Now I see that he made 3 commits and and pushes with deployment to the production server within 5 minutes.

I told him few times that this is not the way how good work is done. I don't want to be rude to him again and he is in the same status with me in the company and he has worked more than me here.

I want this behavior to be punished in some way or make it unpleasant as much as possible.

Before I started, the company was deploying using antique methods, such as FTP, and there was no version control.

I forced them/us to use Git, Bitbucket, Dploy.io, and HipChat. The deployment is not automatic, someone has to login to dply.io and press the deploy button.

Now, how can I force them to not test on the production server? Something like HipChat bot can sense that there is repeated edits on the same line and send a notice to the programmer.


答:
No, Assuming you can't change the base class, or know that one constructor chains to the others. There's no way to choose one of multiple base constructors from another constructor. I thought you might be able to do it with generics, but apparently not.

Even if you use a factory or builder class, where you can call a create method and switch between constructors that it uses within that method, you don't solve your immediate problem. As you still require multiple constructors in your SpecialImage Class

One solution is to wrap your base class rather than inheriting it. This assumes the base class implements an interface, or you can add one on

```<code>using System;

namespace LessConstructors
{
    public class Size
    { }
    public class Thing
    { }
    public class Gray
    { }

    public interface IImage
    {
        object MethodX();
    }

    public class Image<TColour, TDepth> : IImage
    {
        public Image() { }

        public Image(Size size) { }

        public Image(int width, int height) { }

        public Image(string filename) { }

        public Image(TDepth[,,] data) { }

        public object MethodX()
        {
            throw new NotImplementedException();
        }
    }

    public interface IConstructor<T1, T2>
    {
        Image<T1, T2> Create();
    }
    public class SizeConstructor<T1, T2> : IConstructor<T1, T2>
    {
        public Size size { get; set; }

        public Image<T1, T2> Create()
        {
            return new Image<T1, T2>(this.size);
        }
    }

    public class HeightAndWidthConstructor<T1, T2> : IConstructor<T1, T2>
    {
        public int Height { get; set; }
        public int Width { get; set; }

        public Image<T1, T2> Create()
        {
            return new Image<T1, T2>(this.Height, this.Width);
        }
    }

    public class SpecialImage<TDepth> : IImage
        where TDepth : new()
    {
        private Image<Gray, TDepth> image;
        Thing _stuff;
        int _range;

        public SpecialImage(Thing stuff, int range, IConstructor<Gray, TDepth> constructor)
        {
            _stuff = stuff;
            _range = range;
            image = constructor.Create();
        }

        public object MethodX()
        {
            return this.image.MethodX();
        }
    }
}
</code>```

Body:
No, Assuming you can't change the base class, or know that one constructor chains to the others. There's no way to choose one of multiple base constructors from another constructor. I thought you might be able to do it with generics, but apparently not.

Even if you use a factory or builder class, where you can call a create method and switch between constructors that it uses within that method, you don't solve your immediate problem. As you still require multiple constructors in your SpecialImage Class

One solution is to wrap your base class rather than inheriting it. This assumes the base class implements an interface, or you can add one on

using System;

namespace LessConstructors
{
    public class Size
    { }
    public class Thing
    { }
    public class Gray
    { }

    public interface IImage
    {
        object MethodX();
    }

    public class Image<TColour, TDepth> : IImage
    {
        public Image() { }

        public Image(Size size) { }

        public Image(int width, int height) { }

        public Image(string filename) { }

        public Image(TDepth[,,] data) { }

        public object MethodX()
        {
            throw new NotImplementedException();
        }
    }

    public interface IConstructor<T1, T2>
    {
        Image<T1, T2> Create();
    }
    public class SizeConstructor<T1, T2> : IConstructor<T1, T2>
    {
        public Size size { get; set; }

        public Image<T1, T2> Create()
        {
            return new Image<T1, T2>(this.size);
        }
    }

    public class HeightAndWidthConstructor<T1, T2> : IConstructor<T1, T2>
    {
        public int Height { get; set; }
        public int Width { get; set; }

        public Image<T1, T2> Create()
        {
            return new Image<T1, T2>(this.Height, this.Width);
        }
    }

    public class SpecialImage<TDepth> : IImage
        where TDepth : new()
    {
        private Image<Gray, TDepth> image;
        Thing _stuff;
        int _range;

        public SpecialImage(Thing stuff, int range, IConstructor<Gray, TDepth> constructor)
        {
            _stuff = stuff;
            _range = range;
            image = constructor.Create();
        }

        public object MethodX()
        {
            return this.image.MethodX();
        }
    }
}


答:
The main consideration is convenience for the users of your class, which is part of the usability of your API. Too many or too few options could hurt usability. In particular, too many options can confuse users and force them to spend more time choosing. Therefore, you have to consider carefully whether each constructor overload will actually be used. Aggressively remove unused ones before publishing (to internal or external users of the API).

For example, if you provide a constructor that takes a Size, you certainly don't need to provide another constructor that takes int width, int height.

The constructor that takes a string filename is also a bit disingenuous. The colorspace of an image file is decided by the file content. A JPEG file could be gray or YCbCr or YCCK. (YCbCr are customarily auto-converted into RGB upon loading, but there are situations where you need the YCbCr values from the file without the quantization error caused by the conversion.) So, a constructor should not have decided the colorspace without examining the image format first.

I am deeply puzzled by the constructor that doesn't initialize its Image. The rest of your class design seems to imply that its Image must be initialized. Is it your intention to make it a Null Object? If that is not your intention, that constructor shouldn't have existed.

Finally a bit of caution. It looks like you are designing a "single-channel high-dynamic-range" image processing layer on top of an existing library. (Single-channel as in "gray", and high-dynamic-range as in the intention to support 32-bit integer, 32-bit float and 64-bit float.) You might be surprised that some image operations do not support HDR depths at all - in other words, some image operations are limited to TDepth = Byte only. Trying to perform operations on HDR depth might throw an exception at runtime.

I can find a lot of wrongs with the underlying libraries, but I must admit that designing an API for an image library is very difficult. I applaud everyone who made a good effort and shared their work.


答:
This should not work alright.

The dual-maintenance that you mention is not only an annoyance, but a problem that may lead to work duplication while also needing extra work just for syncing the board.

I'm not sure if you remember the CAP theorem from any Databases course, it basically says that your model will fail to be correct, or fast enough if you want it to be distributed (2 boards are enough).

It may not be correct because the possible work duplication, or it may not be 'fast enough' if you have to lock the other board to do some changes on both (maybe fast is not the correct term here, but I promise that keeping the boards on sync will be completely annoying and I would feel sorry for the guy that have to do that).

Title: Is there a practical way to manage a physical task board if one or more scrum team members works remotely?

Body:
I've convinced a few colleagues to try scrum with me, but one of them works remotely. We'd like to try using a physical task board.

I think we might be able to pull it off by snapping a photo and sending it to him every time the board is updated, and when he wants to update any of his tasks at the end of the day, he can just ask me to do it for him. It seems simple enough, but I'm not sure if we would be better off just using an online task board like Trello.

We're also considering managing a physical board and a Trello board but would like to avoid dual maintenance.

Has anyone implemented scrum with a physical task board shared with remote team members? If so, what worked and what didn't work?


答:
Unfortunately there's no great answer to this question.

Physical Board

A physical board has advantages.  It's effortless to radiate, a great place to have conversations around, and promotes a pull-based workflow.  It's completely customizable and you can use whatever rules and flows you want without any impediments.  Edits to current work are easy, no harder than updating a whiteboard.  As an "experienced" board user, my favorite part is that everything is inherently disposable and "hanging on" to backlog is space-prohibitive.  I also like that our inherent laziness makes it so that we'll devolve to using cards as tokens for conversation rather than cramming every last detail onto a 3x5 card.

Virtual Board

A virtual board is easy to share.  Most come with some constraints that arguably make it easier to get started using boards.  Unfortunately, most of them force their style of board-flow on you.  Online systems promote linking things together, ownership, and the ability to archive and hang on to anything.  You can attach all kinds of useful things to the card.  The primary disadvantage for me is that it's easy to "lose" and forget in a browser tab.  I'm also frustrated by the difficulty in finding the "right way" to edit a card because my default method of throwing the old one away is usually punished in strange ways.

In the end, the key question for me is:  Do I want to treat my remote teammates as second-class citizens?  Because that's the reality if there's a "board of record" and it lives on-site.

You can do things to make a virtual board better.  Dedicating monitors or workstations to the board helps with radiating it and promoting conversation.  Making a physical board better for remote workers is tougher.  I've seen people do the remote update of two physical boards, and that process does promote some shared understanding, but it is a significant time investment.


问:
Why does Python need both a compiler and an interpreter?
I can understand the fact that Java needs both a compiler and an interpreter. It compiles source code to bytecode and then a virtual machine (on Windows, on Linux, on Android, etc.) translates that bytecode to machine code for the current architecture.

But why does Python need both a compiler and an interpreter? Since Python is not platform independent, why not just use interpretation? As far as I know, you cannot execute a Python program (compiled to bytecode) on any Windows or Linux machine without modification. Or am I wrong?

答:
It's true that the bytecode is not suitable as a distribution format, but that doesn't mean it's useless. Aside from improving startup time on a given machine, after the first run, interpreting bytecode is also far simpler than interpreting an AST or, god forbid, interpreting line-by-line.

Bytecode is a more low-level, more regular, more compact (both semantically and in terms of memory layout) representation of the code. The order of operations is already spelled out, local variable names have been resolved to a simpler form (integer indices). No complicated syntax to follow, just one simple instruction after another. Additionally, less state is needed: for line-by-line interpreting you basically need to keep a whole parser around, and an AST interpreter blows up the call stack with its tree traversal, whereas a bytecode interpreter just needs a small stack for temporary values and locals.

These and other factors conspire to make bytecode interpreters significantly faster than other interpreters.


答:
As far as I know, you cannot execute a Python program (compiled to
  bytecode) on every machine, such as on windows, or on linux without
  modification.

You are incorrect. The python bytecode is cross platform. See Is python bytecode version-dependent? Is it platform-dependent? on Stack Overflow. However, it is not compatible across versions. Python 2.6 cannot execute Python 2.5 files. So while cross-platform, its not generally useful as a distribution format.

But why Python needs both a compiler and an interpreter?

Speed. Strict interpretation is slow. Virtually every "interpreted" language actually compiles the source code into some sort of internal representation so that it doesn't have to repeatedly parse the code. In python's case it saves this internal representation to disk so that it can skip the parsing/compiling process next time it needs the code.

Title: Why does Python need both a compiler and an interpreter?

Body:
I can understand the fact that Java needs both a compiler and an interpreter. It compiles source code to bytecode and then a virtual machine (on Windows, on Linux, on Android, etc.) translates that bytecode to machine code for the current architecture.

But why does Python need both a compiler and an interpreter? Since Python is not platform independent, why not just use interpretation? As far as I know, you cannot execute a Python program (compiled to bytecode) on any Windows or Linux machine without modification. Or am I wrong?