答:
While I agree with James, sometimes for whatever reasons you may want to have objects, so as to have a better representation of the actual data.

In those cases, there are two considerations:

Having just CategoryId, if you laways or almost always need the name, will require another request;

Having both options is pretty useless since Post.CategoryId is not really that different from Post.Category.Id, and you have a structure that makes sense, no matter if you have arrays, objects or whatever.

Taking these points into account, in this specific case I would go with nested objects. You have cleaner code, you can easily understand data structures from the JSON (Less mistakes and easier to build new stuff or fix it) and you're avoid unnecessary duplication, in your code and in the JSON object.

Still, it's always good to remember that sometimes nested objects may not be the best option, performance-wise. It's all a matter of what works better for your specific situation.

Title: Representing a "Belongs to" relationship in an API endpoint

Body:
Consider the following pseudo code models:

```<code>class Post
    int Id
    string Title
    int CategoryId
    Category Category

class Category
    int Id
    string Name
</code>```

Note that Post belongs to Category. This is achieved via a CategoryId foreign key on Post. In the post model, there's also a Category object.

So my questions are:

1. On a GET request for a post, what would your JSON look like?

A - Just the foreign key (this one seems a little inefficient if the value for the Category name is commonly needed)

```<code>{
  Id: 1,
  Title: 'My Title',
  CategoryId: 1
}
</code>```

B - Just the nested object

```<code>{
  Id: 1,
  Title: 'My Title',
  Category: {
    Id: 1,
    Name: 'General'
  }
}
</code>```

C - Both (same as the actual model)

```<code>{
  Id: 1,
  Title: 'My Title',
  CategoryId: 1,
  Category: {
    Id: 1,
    Name: 'General'
  }
}
</code>```

2. Considering the above, what do you do for a PUT/POST?

I can't seem to find any concrete examples of the best practice to represent this case. Any thoughts, guidance or discussion welcome!


问:
Representing a "Belongs to" relationship in an API endpoint
Consider the following pseudo code models:

```<code>class Post
    int Id
    string Title
    int CategoryId
    Category Category

class Category
    int Id
    string Name
</code>```

Note that Post belongs to Category. This is achieved via a CategoryId foreign key on Post. In the post model, there's also a Category object.

So my questions are:

1. On a GET request for a post, what would your JSON look like?

A - Just the foreign key (this one seems a little inefficient if the value for the Category name is commonly needed)

```<code>{
  Id: 1,
  Title: 'My Title',
  CategoryId: 1
}
</code>```

B - Just the nested object

```<code>{
  Id: 1,
  Title: 'My Title',
  Category: {
    Id: 1,
    Name: 'General'
  }
}
</code>```

C - Both (same as the actual model)

```<code>{
  Id: 1,
  Title: 'My Title',
  CategoryId: 1,
  Category: {
    Id: 1,
    Name: 'General'
  }
}
</code>```

2. Considering the above, what do you do for a PUT/POST?

I can't seem to find any concrete examples of the best practice to represent this case. Any thoughts, guidance or discussion welcome!

答:
Structurally, I would reconsider the notion that a post belongs to a category. That's a strange way to model the relationship, especially considering a post very well may form a relationship with multiple categories. So in my mind a post has multiple categories.

As @James Anderson initiated, you shouldn't think about your API as a result of your persistence structure. Rather, create your API first and later figure out how to query your persistence layer to formulate the response you want.

If I were designing this API then I would just return an array of category titles as a property of the post object. The IDs probably aren't necessary.

For POST and PUT you can either accept category titles and map them to IDs on the back end (returning an error code or possibly creating a new category if a provided title doesn't exist), or accept a category ID. In case of the latter, you'll want a separate API to to GET all known categories and their IDs.

ContentLicense: CC BY-SA 3.0


问:
Documenting intent Vs knowledge
It is said you should document the intent of your function or class which I agree with. However recently this line became a little bit blurred when I was wanting someone to document why this particular class is being created.

Specific example:

```<code>public class SMSException extends Exception{.....}
</code>```

In the above case there is no added code, each constructor is called with super(...)

To those familiar with throwing exceptions, creating a specific exception to throw makes perfect sense. (which is why we can throw exceptions like IllegalArgumentException, NumberFormatException etc... instead of just Exception)

Documenting the intent here seems overboard as the documentation will be the same as the class it is extending... But at times it seems appropriate to document this knowledge purely so that when new developers still finding their feet come across this can understand why this is done and not just wonder why people are doing this or what the advantage of doing this is.

So the question: Is it good practise to document that bit of knowledge here or should that knowledge remain in the lectures halls, training manuals, google, colleagues, etc... ?

答: I think that 'SMSException' is ok as a class name, but definitely could use more explanation as to what it means. An error sending an sms? Receiving one? Parsing one with a particular format? Not receiving one when expected?</p>

Title: Documenting intent Vs knowledge


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
Programming abstractions are abstractions made by someone on a programatical element. Lets say you know how to build a Menu with it's items and stuff. Then someone saw that piece of code and thought, hey that could be useful in other kind of hireachy-like structures, and defined the Component Design Pattern with is an abstraction of the first piece of code.

Object Oriented Design Patterns are quite a good example of what is abstraction, and i dont mean the real implementation but the way we should approach a solution.

So, to sum up, programming abstraction is an approach that allows us understand a problem, it is the means to get something but it aint the real thing

Title: What is abstraction?

ContentLicense: CC BY-SA 2.5


问:
Definition of the NHibernate Mapping by Code / EF Code First pattern?
Sub-questions:

Does this pattern have a formal definition?

Who invented it?

Is it considered a DSL?

The reason why I am asking is because I would like to better assess its applicability to non-classic-DB scenarios, for example as an alternative to configuration files with a custom format, that don't need to be changeable after compilation.

答: Not sure if this answers your question appropriately, but I would advise against using EF or Nhibernate or any other large ORM for non classic DB structures. I highly suggest using a microORM such as Dapper, petaPOCO, or Susanoo (full discretion Susanoo is my open source project). EF for instance has some pretty stringent rules and conventions that don't play well if you don't design your DB as it expects.</p>


问:
Which design pattern for a single class accessing an object representing a data structure?
Which design pattern should I use when I have a class representing a data structure (aka C-style struct) and I wish to have only a single class to be able to access it.

I was thinking of simply declaring the class that represents a data structure as an inner class but wanted to know if there is a better way to design this.

eg:

```<code>class XXManager{
getXX();
setXXAtrtribute();
}

class XX{
  String name;
  String email;
  String job;
}
</code>```

Here I want to design a class XXManager which will handle the creation and managment of 'XX' objects and no one should be able to access XX other than through the XXManager.

答:
Cannot quickly find any links, but I was taught that naming something an XXManager is a "code smell" and you should strongly consider naming it XX.

Why do you want an Anemic class XX with a separate XXManager?

Sometimes it makes sense to have a separate manager, e.g. if you are religiously following MVC, or a Database is involved, but is that the case here?

Assuming you want to do this, an inner class is one solution.  Alternatively, in Java you could put all the classes in the same package and use package access.  That isn't perfect, as an unscrupulous hacker could create a rogue class in the same package and abuse your data.  So don't do that if you are creating some security library.  Bu if the code is internal and you trust your fellow coders it is a good solution.


问:
classes/inheritance, how do I handle special cases that require more change
I often find myself in this situation where I have a base class that does a lot of graphics. There are, for example, three strings that are positioned top, middle, bottom of an element. Like a scale or something. Now for every type of scale I make a new class that inherits the base class and simple sets the three strings and everything is fine. But often there is ONE single case, where I need four strings.

Sure, I could just override the method and recalculate for four, BUT if the calculations are based on a lot of offsets etc I would always have to take a look at how the base class does it in the first place and then copy-paste the entire calculation and do it for one more string. This means that every time the base calculation changes, I would need to copy-paste again etc.

On the other hand I could write the base class so super flexible that every tiny step can be overridden and subclasses can do everything they want with ease. But this requires way more work on the base class for ONE special case out of 20.

So either it's more workload in the beginning or the risk of missing a copy paste.

Often I don't even know what will come and you can't write a baseclass that is all-flexible and no one has the time to do so. So overriding and copy-pasting seems the best way to do so, but it still seems way too risky.

How should I approach this? I am looking for solutions that are practical, not a schoolbook approach that is too time consuming in a real work life.

(I mainly work with Java)

Edit:
To get a bit away from my example, which is really just an example.
Let's say i have a class and 20 subclasses and they work. Now along comes a new subclass that needs ONE thing completely different and just can't use the base classes method. If i override i have to copy paste the entire method and adapt it. If i change anything about the method, then i will have to change 20 classes that are already working fine.

"Do it from the start" works with one method, but what if 10 or more methods could be the cause for trouble. I can't write the base class in a way that for every method a variable-method-class can be used. I could, but that's what i meant above with "extreme workload at the beginning"

答:
The textbook answer to your question is to "use composition over inheritance".

Instead of copy-pasting like crazy or trying to overdesign the ultimate base class, make pieces that solve parts of the problem and put them together.

Using your example, a part that might make sense would be a function that takes a string length, font, etc. and calculates the size of an onscreen rectangle that would fit it.  Another part might be a function that takes a list of rectangles to be stacked on top of each other, and figures out a visually pleasing way of arranging them.  By putting the parts together, you can now calculate a layout for your strings easily, and there's no difficulty going from 3 strings to 4 strings (especially if you just make a list of the strings in the first place and don't worry about how many of them there are).

Oh, but now we have to support icons, too.  No problem, just make a function that takes an icon and returns its rectangular size, then use the rectangle normally.  Adding new stuff doesn't involve changing working code, you just add a new piece or use the existing pieces differently.


问:
How to minimize database deadlocks in a load balanced web application?
I'm working on a web application hosted on multiple load-balanced web front ends (WFEs). This application has an API method that performs a database query and returns the results. This query only performs reads. There is a single database server.

We are finding that when the API method is called in quick succession and the requests are distributed across the WFEs, the database queries that execute will intermittently deadlock.

There are occasional writes to the database that occur from other parts of the system. I haven't yet verified if they are occurring at the same time.

Load is increasing and this issue is likely to occur more frequently over time. We have optimised the query and query transaction settings as best we can.

Is there a more appropriate architecture for this scenario?

(The technologies involved are MS .NET / Web API / SQL Server 2008 R2 although we're open to any options.)

答:
Scaling is hard.

Scaling databases is even harder.

If you have enough calls to often have simultaneous calls to database, even if you can avoid deadlocking it won't solve your problem, as latency will start to increase.

You probably need another database server, and that comes with a ton of stuff to change to work with a cluster. I would take this chance to look into other databases, such as NoSQL databases aor maybe PostGreSQL. They may be a game-changer.

Also, caching models (I.e. something like Redis caching results for the most usual queries) may help a lot.


问:
What principle is violated by having a button do two radically different things or screens act radically different depending on the situation
I've come upon a situation several times in my career when previous developers have done something funny.

They will make a control (button) function radically different depending on how the screen was opened or some other condition in the data (e.g., save the data to a txt file vs. do a recalculation of something and store it in a database field). If you're lucky, they've changed the caption on the button when they change the functionality.

I've also seen them change the layout of the screen (hide controls, rename them, show entirely new sections). Again, likewise often they change the window caption.

This seems to be an anti-pattern because it make it hard for future developer to figure out what any one screen/control does without extensively walking the code and testing. And the temptation that they are falling for that they think they are saving the time to create a second form by creating one that works differently for different conditions.

What principle is being violated here? I know of the Single Responsibility Principle; but it doesn't seem to be a perfect fit. I think it's closer to "don't do this because it confuses the heck of the users", but I'm not sure if there is anything formal I can point to.

答:
It's consistency, or also "principle of least astonishment".

However, your less formal definition seems fine too, more pragmatic.


问:
Efficient datastructure to create size-limited dictionary
I need a class that acts like a dictionary but will constrain the total number of key/value pairs it contains. For instance, let's say the maximum number of entries is 1000 and the class already contains 1000 key/value pairs. If I add an additional key/value pair, the class should remove the key-value pair that was updated least recently.

Here's my current implementation in python:

```<code>class SizeLimitedDefaultDict(defaultdict):
    last_changed = []

    def __init__(self, default, max_size, *args, **kwargs):
        max_size = 0
        super(SizeLimitedDict, self).__init__(default, *args, **kwargs)

    def __setitem__(self, key, val):
        if len(self) >= self.max_size:
            remove_oldest_entry()
        super.__setitem__(self, key, val)
        update_newest_entry(key)

    def update_newest_entry(self, key):
        key_index = last_changed.index(key) #will slow it down
        last_changed.insert(0, last_changed.pop(key_index))
</code>```

This clearly isn't a viable solution. All the performance gains of the dictionary are lost. I'm having trouble figuring out a better solution though. Is there a data structure that can easily maintain which keys have been most recently updated.

答:
You should store the keys in two structures simultaneously -- a tree (or heap), and a doubly-linked list.  Each node of the tree must include a pointer to the corresponding entry in the linked list.  The values should be stored with the tree nodes; the list entries need only the keys.

To look up a value, the linked list need not be consulted or altered.

To update a key/value pair, find it in the tree and overwrite its value.  Then use its list pointer to identify the corresponding list entry.  Unlink the entry from its current location and link it to the end of the list.  This action maintains the list in update order.

To identify the least recently updated entry, simply read the key from the first item in the linked list.

I think you know the rest.  Look up that node in the tree, overwrite its key and value, and move it to its proper place in the tree, but without altering its list pointer.  Also overwrite the key in the list entry, and don't neglect to unlink it and move it to the end of the list.


问:
What is the effectiveness of code reviewing by just reading?
I have been given the task of reviewing a change request comprising of more than 20 changes, the problem is that we do not / cannot install a version of the software to be evaluated as the development environment cannot be easily re-created or installed. My question is, aside from just reviewing language grammar, is it really effective to review changes just by reading the code instead of by reading, running the code, and reading again?</p>

答:
is it really effective to review changes just by reading the code (...)?

If you have enough practice coding you will be able to spot bugs without software/coding environment. It's good practice to read raw text and try to pick out the errors (logic or syntax). It will help you become a stronger programmer.


问:
Filling the gap between Conception and Unit Test
I am stuck trying to do TDD. I'd rather seek the counsel of others who have gone before rather than waste time with trial and error.

QUESTION:

What diagrams / exercises / development processes can I insert between "foggy notion of what system is supposed to do" (aka Conception) and "Write Test"?

Anything else included in this question is simply additional information to help communicate / clarify my question; not to change the question in any way. I do not care what diagrams / exercises / development processes I use, as long as they get me unstuck.

When I say Conception I just mean a foggy informal mental-only notion of what a system should / can / will / might do.

FORM OF ANSWER:

I'm trying to navigate from conception to Unit Test in my development process. I'm looking for a way, a path, a road map, a bridge. An answer might look something like this:

do a xyxyx type diagram to get the aaaas, then take all the
  aaaas and do a wywywyw diagram, then all the ccccs on the
  wywywyw diagram will be the classes you need to unit test and the
  lllllls will be the scenarios of the tests.

PROBLEM BACKGROUND:

I found a TDD flowchart and converted it to a Google Drawing. I'm using NUnit. I have studied TDD, know what it is and practiced it somewhat. This flow chart is for TDD only; no steps before Unit Testing are included.

The flowchart starts out with "Write Test". I had my concept, nothing I had read said I needed anything else first, so I tried following the flow chart. It was too much of a leap to go from "foggy notion" to Unit Test. This caused me "designer's block". Then I read someone say "just do it!" I tried that, but the resulting tests and ensuing code wandered somewhat aimlessly since there was nothing to guide what tests to write.

ATTEMPTS AT SOLUTION:

Some ideas I have explored already that seem helpful (but the question is not about these things):

BDD (I used SpecFlow)

use case diagrams

SpecFlow starts with a verbal description of a "feature" and creates tests that NUnit can run; they don't look like the unit tests I created manually but maybe I'll figure out how they relate to one another.

Use cases helped me get convert the initial foggy notion into a formal description, which was a bit of sunshine. I used Visual Studio 2013 for that. I don't see any facility (in Visual Studio at least) to convert my use case into Unit Tests, although I found some evidence that this is one purpose of a use case. Quoting from the UML User Guide, 2nd ed., p.246:

A use case diagram can be forward engineered to form tests for the
  element to which it applies.

And it looks like Visual Studio maybe wants to convert it because it can store template data on the use case and has "Code Generation Settings"

Here is a picture of what I have tried so far

答:
You cannot jump directly from "idea" to "implementation". Good example is the "V model" :

You start at high level go lower and you write tests on each level. And each level gets more specific in both implementation and testing. For example you write an acceptance test that says that you should be able to add a customer. This results in you writing an integration tests to ensure client can be both created and inserted into database. And this forces you to write unit tests that describe detailed conditions for creating and saving the customer object. And then you implement the code until unit test pass, this will make integration tests pass and that will make acceptance tests pass. So you get few high-level acceptance tests, more integration tests and lots of small and detailed unit tests.

OwnerDisplayName: toddmo


答:
Where I work, the author of the code changes is responsible for testing that those changes actually work, while the code reviewer is typically responsible for finding any issues with the readability/maintainability of those changes or spotting corner cases the author might not have thought to test for. In general, the reviewer looks for the sort of problems that the author is most likely to miss precisely because he wrote it. So it's completely okay for the reviewer to not test the changes, as long as the original author did test them.

And when the change is not to UI code, there should be unit tests, so it is also the author's responsibility to add or change a test to prove the code works as intended, and actually run the tests to make sure they all still pass. The reviewer will then check for readability/maintainability issues or missed corner cases within that test as well as in the "real" code changes. Though running a subset of the unit tests is so quick and easy that I usually do that myself when I'm reviewing something, even though I technically don't need to.

There are occasions where one of us really wants the reviewer to test it, because it's the sort of UI change that can't be effectively tested in any automated way, and at least two people need to bang on for a minute to prove it didn't break anything. In those cases we explicitly ask the reviewer to do that.

Title: What is the effectiveness of code reviewing by just reading?

Body: I have been given the task of reviewing a change request comprising of more than 20 changes, the problem is that we do not / cannot install a version of the software to be evaluated as the development environment cannot be easily re-created or installed. My question is, aside from just reviewing language grammar, is it really effective to review changes just by reading the code instead of by reading, running the code, and reading again?</p>


答:
In our team, the style and general coding rules are checked by code analyzers with every build. Therefore when we review the code, mostly the code written by juniors, we try to spot the parts that does not follow the architecture and design patterns because these cannot be checked automatically by tools easily.

We don't run the code because it is mandatory to write tests and have a code coverage above 80%. But we also review the tests as much as the implementation. This is the most beneficial part to discover possible design problems.

If a unit test is not clear and it is bulky, generally the implementation is also not ideal. So we tend to review tests first.


答:
Code review is mostly about the readability and maintainability of the code. You also have a sanity check on whether the changes relate in any way to the actual change request.

If it confuses the code reviewer it will probably confuse any one who has to amend the code subsequently.

Yes code reviews can pick up other potential bugs, but most of these could be picked up by various source code analysis tools anyway.

The actual major benefit of code reviews is the coders write better code if they know another human is going to read it and ask "why did you stored the sales tax in a field call "bonus"" type questions.


问:
Why use atomic vectors or matrices in R at all?
In reading Hadley Wickham's Advanced R I learned about the difference between atomic vectors and lists; and matrices/arrays and dataframes. This is something I hadn't really appreciated before, and seems to make sense.

My question is, if lists and dataframes are more flexible (i.e. they allow multiple data types) why use atomic vectors and matrices at all if they are more restrictive?

I guess it may affect performance, but I don't know.

答:
I asked Hadley Wickham on Twitter who replied:

@philmikejones data frames are built with atomic vectors + you always want to use simplest thing that works
— Hadley Wickham (@hadleywickham) March 18, 2015


问:
Asp.net caching strategy/pattern
In my WebApi controller I have the following (pseudo) code that receives update notifications from Instagrams real-time API:

```<code>[HttpPost]
public void Post(InstagramUpdate instagramUpdate)
{
    var subscriptionId = instagramUpdate.SubscriptionId;
    var lastUpdate = GetLastUpdate(subscriptionId);

    // To avoid breaking my Instagram request limit, do not fetch new images too often.
    if (lastUpdate.AddSeconds(5) < DateTime.UtcNow)
    {
        // More than 5 seconds ago since last update for this subscription. Get new images
        GetNewImagesFromInstagram(subscriptionId);
        UpdateLastUpdate(subscriptionId, DateTime.UtcNow);
    }
}
</code>```

This won't work very well if I receive two update notifications for the same subscription almost simultaneously, since lastUpdate won't have been updated until after the first request has been processed. And even if I update lastUpdate directly, there is a "lag" because of the round trip to the database.

What would be the best way to tackle this problem? I'm thinking of using some kind of cache (that would be faster than the database roundtrip), but I'm not sure how. Is there some kind of best practices for these kind of things? I'm guessing it's a common problem: "receive notification, do something if something hasn't been done recently..."

答:
I have another suggestion for the mechanism: when an update arrives, mark a subscription as having to update, and wait for your delay before making the update. That is, there is no need for a cache, you only need to store some state for each subscription id as "having to update" or not.

I will use async because it makes the code pretty straightforward.

For example:

```<code>private struct Empty {}
private ConcurrentDictionary<int, Empty> subscriptionsToUpdate = new ConcurrentDictionary<int, Empty>();

[HttpPost]
public async Task PostAsync(InstagramUpdate instagramUpdate)
{
    var subscriptionId = instagramUpdate.SubscriptionId;

    if (subscriptionsToUpdate.TryAdd(subscriptionId, default(Empty)) {
        await Task.Delay(TimeSpan.FromSeconds(5));

        if (subscriptionsToUpdate.TryRemove(subscriptionId)) {
            GetNewImagesFromInstagram(subscriptionId);
            UpdateLastUpdate(subscriptionId, DateTime.UtcNow);
        }
    }
}
</code>```

Note that the implementation here only considers requests that are handled by a single Web API process. (E.g. if you have multiple servers, that code would potentially make one request, every five seconds, for each server that you have. If you want to avoid that, you would have to use some kind of shared store instead of a ConcurrentDictionary. (I would recommend something like a key value store, like Redis or memcached.))

Title: Asp.net caching strategy/pattern

Body:
I have another suggestion for the mechanism: when an update arrives, mark a subscription as having to update, and wait for your delay before making the update. That is, there is no need for a cache, you only need to store some state for each subscription id as "having to update" or not.

I will use async because it makes the code pretty straightforward.

For example:

private struct Empty {}
private ConcurrentDictionary<int, Empty> subscriptionsToUpdate = new ConcurrentDictionary<int, Empty>();

[HttpPost]
public async Task PostAsync(InstagramUpdate instagramUpdate)
{
    var subscriptionId = instagramUpdate.SubscriptionId;

    if (subscriptionsToUpdate.TryAdd(subscriptionId, default(Empty)) {
        await Task.Delay(TimeSpan.FromSeconds(5));

        if (subscriptionsToUpdate.TryRemove(subscriptionId)) {
            GetNewImagesFromInstagram(subscriptionId);
            UpdateLastUpdate(subscriptionId, DateTime.UtcNow);
        }
    }
}

Note that the implementation here only considers requests that are handled by a single Web API process. (E.g. if you have multiple servers, that code would potentially make one request, every five seconds, for each server that you have. If you want to avoid that, you would have to use some kind of shared store instead of a ConcurrentDictionary. (I would recommend something like a key value store, like Redis or memcached.))


问:
What is the name of a function that takes no argument and returns nothing?
In Java 8's java.util.function package, we have:

Function: Takes one argument, produces one result.

Consumer: Takes one argument, produces nothing.

Supplier: Takes no argument, produces one result.

...: Other cases handling primitives, 2 arguments, etc...

But I need to handle the "takes no argument, produces nothing" case. There is nothing for this in java.util.function.

So, the question is: What is the name of 'a function that takes no argument and returns nothing'?

In Java 8, its definition would be:

@FunctionalInterface
public interface InsertANameHere {
    void execute();
}
```

Executor already exists and has another purpose : "An object that executes submitted Runnable tasks". The signature doesn't match (execute(Runnable):void) and is not even a functional interface.

Runnable exists, but it is strongly linked to the threading context:

The package is java.lang, not java.util.function.

The Javadoc states : "The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread".

The name "Runnable" suggest some running code inside a thread.

答:
Why not Command? Given that it takes no data and returns no data, but assuming that calling it causes some effect (otherwise it would be rather pointless really), I imagine that's roughly the only thing it can do - fire an action, make something happen.

Speaking of which, there's also a generic Action delegate in .NET. Unlike Java's Consumer it can take from 0 to 16 arguments; in other words, the simpliest version of it takes none - see MSDN.

And since the name doesn't imply there's anything to "consume", it also seems like a good name choice.

ContentLicense: CC BY-SA 4.0


问:
Why do you need higher kinds?
Some languages allow for classes and functions with type parameters (such as List<T> where T may be an arbitrary type). For example, you can have a function like:

```<code>List<S> Function<S, T>(List<T> list)
</code>```

Some languages however allow this concept to be extended one level higher, allowing you to have a function with the signature:

```<code>K<S> Function<K<_>, S, T>(K<T> arg)
</code>```

Where K<_> itself is a type like List<_> that has a type parameter. This "partial type" is known as a type constructor.

My question is, why do you need this ability? It makes sense to have a type like List<T> because all List<T> are almost exactly the same, but all the K<_> can be entirely different. You can have an Option<_> and a List<_> that have no common functionality at all.

答:
Since no one else has answered the question, I think I'll give it a go myself. I'm going to have to get a bit philosophical.

Generic programming is all about abstracting over similar types, without the loss of type information (which is what happens with object-oriented value polymorphism). In order to do this, the types must necessarily share some sort of interface (a set of operations, not the OO term) that you can use.

In object-oriented languages, types satisfy an interface by virtue of classes. Each class has its own interface, defined as part of its type. Since all classes List<T> share the same interface, you can write code that works no matter which T you choose. Another way to impose an interface is an inheritance constraint, and although the two seem different, they are sort of similar if you think about it.

In most object-oriented languages, List<> is not a proper type in itself. It has no methods, and thus has no interface. It is only List<T> that has these things. Essentially, in more technical terms, the only types you can meaningfully abstract over are those with the kind *. In order to make use of higher-kinded types in an object-oriented world, you have to phrase type constraints in a manner consistent with this restriction.

For example, as mentioned in the comments, we can view Option<> and List<> as "mappable", in the sense that if you have a function, you could convert an Option<T> into an Option<S>, or a List<T> into a List<S>. Remembering that classes cannot be used to abstract over higher-kinded types directly, we instead make an interface:

```<code>IMappable<K<_>, T> where K<T> : IMappable<K<_>, T>
</code>```

And then we implement the interface in both List<T> and Option<T> as IMappable<List<_>, T> and IMappable<Option<_>, T> respectively. What we've done, is using higher-kinded types to place constraints on the actual (non-higher-kinded) types Option<T> and List<T>. This is how it's done in Scala, though of course Scala has features such as traits, type variables, and implicit parameters that make it more expressive.

In other languages, it is possible to abstract over higher-kinded types directly. In Haskell, one of the highest authorities on type systems, we can phrase a type class for any type, even if it has a higher kind. For example,

```<code>class Mappable mp where
    map :: mp a -> mp b
</code>```

This is a constraint placed directly on an (unspecified) type mp which takes one type parameter, and requires it be associated with the function map that turns an mp into an mp. We can then write functions that constrain higher-kinded types by Mappable just like in object-oriented languages you could place an inheritance constraint. Well, sort of.

To sum things up, your ability to make use of higher-kinded types depends on your ability to constrain them or to use them as part of type constraints.

Title: Why do you need higher kinds?

Body:
Since no one else has answered the question, I think I'll give it a go myself. I'm going to have to get a bit philosophical.

Generic programming is all about abstracting over similar types, without the loss of type information (which is what happens with object-oriented value polymorphism). In order to do this, the types must necessarily share some sort of interface (a set of operations, not the OO term) that you can use.

In object-oriented languages, types satisfy an interface by virtue of classes. Each class has its own interface, defined as part of its type. Since all classes List<T> share the same interface, you can write code that works no matter which T you choose. Another way to impose an interface is an inheritance constraint, and although the two seem different, they are sort of similar if you think about it.

In most object-oriented languages, List<> is not a proper type in itself. It has no methods, and thus has no interface. It is only List<T> that has these things. Essentially, in more technical terms, the only types you can meaningfully abstract over are those with the kind *. In order to make use of higher-kinded types in an object-oriented world, you have to phrase type constraints in a manner consistent with this restriction.

For example, as mentioned in the comments, we can view Option<> and List<> as "mappable", in the sense that if you have a function, you could convert an Option<T> into an Option<S>, or a List<T> into a List<S>. Remembering that classes cannot be used to abstract over higher-kinded types directly, we instead make an interface:

IMappable<K<_>, T> where K<T> : IMappable<K<_>, T>

And then we implement the interface in both List<T> and Option<T> as IMappable<List<_>, T> and IMappable<Option<_>, T> respectively. What we've done, is using higher-kinded types to place constraints on the actual (non-higher-kinded) types Option<T> and List<T>. This is how it's done in Scala, though of course Scala has features such as traits, type variables, and implicit parameters that make it more expressive.

In other languages, it is possible to abstract over higher-kinded types directly. In Haskell, one of the highest authorities on type systems, we can phrase a type class for any type, even if it has a higher kind. For example,

class Mappable mp where
    map :: mp a -> mp b

This is a constraint placed directly on an (unspecified) type mp which takes one type parameter, and requires it be associated with the function map that turns an mp<a> into an mp<b>. We can then write functions that constrain higher-kinded types by Mappable just like in object-oriented languages you could place an inheritance constraint. Well, sort of.

To sum things up, your ability to make use of higher-kinded types depends on your ability to constrain them or to use them as part of type constraints.


问:
Design ideas - validation based on conditions outside of the domain
I am facing a very interesting problem here, and I'd like to see some design ideas from domain driven design perspective.

To make it easier to express what I need I have following hypothetical situation. I have a bounded-context named Customer, which is used to handle create new customer, update customer, searching customer and so on. I have a customer class look like

```<code>public class Customer
{
    public int Id { get; set ; }
    public int SocialInsuranceNumber { get; set ; }

    public bool IsValid()
    {
        // my logic to validate social insurance number
    }
}
</code>```

So I have a straightforward logic in my entity to validate the data. The Canadian Social Insurance Number validation rule indicates all values begins with 0 should not be used, but Canadian government might use it for some reason. So there are possible 2 validation rules here now.

The business has the requirement of one single application - for majority of the situations when user enters a social insurance number we have to make sure the value cannot start with 0 and the value must be a valid SIN, but in some unique situation we must allow a valid SIN starting with 0.

My domain service code looks like

```<code>public class CustomerService
{
    public void AddCustomer(Customer customer)
    {
        if (customer.IsValid())
        {
            // save to database
        }
    }
}
</code>```

If I add a boolean parameter to Customer class's IsValid() function to make to look like IsValid(bool allowLeadingZero), I could make the code work. But I think it looks ugly.

From design perspective how would you suggest a more elegant way to deal with such requirement?

答:
Well, I don't see any problem here, actually.

To consider something to be a validation rule of the object, you must be able to take an object and tell me exactly how do you validate this object to satisfy the rule. In your case there is no condition clearly defined when to apply this rule, so I would say you have no validation rule at all ;)

...in some unique situation...

So, make a flag of such a situation part of object state. And then you will be able to apply validation rule over it.


答: I would argue if there is a piece of code you need to run or debug first to understand what it does, the code has to be improved in terms of readability, and the review which has revealed that was quite effective.</p>


答:
Java's choice to do it that way with a separate name for every arity was not exactly worth emulating.  However, if you must for the sake of consistency, or if you're writing very generic library code, Konrad's suggestions are good.  I might throw Procedure into the ring.

Using a pseudo-functional paradigm doesn't mean normal naming principles should go out the window.  Interfaces should almost always be named after what they do, not after some generic syntactic idea.  If the functions are placed into an undo stack, they should be named UndoFunction.  If they are called from GUI events, they should be named GUIEventHandler.

Title: What is the name of a function that takes no argument and returns nothing?

Body:
In Java 8's java.util.function package, we have:

Function: Takes one argument, produces one result.

Consumer: Takes one argument, produces nothing.

Supplier: Takes no argument, produces one result.

...: Other cases handling primitives, 2 arguments, etc...

But I need to handle the "takes no argument, produces nothing" case. There is nothing for this in java.util.function.

So, the question is: What is the name of 'a function that takes no argument and returns nothing'?

In Java 8, its definition would be:

@FunctionalInterface
public interface InsertANameHere {
    void execute();
}
```

Executor already exists and has another purpose : "An object that executes submitted Runnable tasks". The signature doesn't match (execute(Runnable):void) and is not even a functional interface.

Runnable exists, but it is strongly linked to the threading context:

The package is java.lang, not java.util.function.

The Javadoc states : "The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread".

The name "Runnable" suggest some running code inside a thread.


问:
Which management book would you recommend to read for a fresh Team Leader?
Which management book would you recommend to read for a fresh Team Leader?</p>

答: AntiPatterns in Project Management is a wonderful list of ways to do things wrong.  It's a great list of things to avoid.  </p>


问:
Is it better to use preprocessor directive or if(constant) statement?
Let's say we have a codebase that is used for many different costumers, and we have some code in it that is relevant only for costumers of type X. Is it better to use preprocessor directives to include this code only in costumer of type X, or to use if statements? To be clearer:

```<code>// some code
#if TYPE_X_COSTUMER  = 1
// do some things
#endif
// rest of the code
</code>```

or

```<code>if(TYPE_X_COSTUMER) {
    // do some things
}
</code>```

The arguments I can think about are:

Preprocessor directive results in smaller code footprint and less branches (on non-optimizing compilers)

If statements results with code that always compiles, e.g. if someone will make a mistake that will harm the irrelevant code for the project he works on, the error will still appear, and he will not corrupt the code base. Otherwise he will not be aware of the corruption.

I was always been told to prefer the usage of the processor over the usage of the preprocessor (If this is an argument at all...)

What is preferable - when talking about a code base for many different costumers?

答:
A few additional points worthy of mention:

The compiler can process some kinds of constant expressions which the preprocessor cannot.  For example, the preprocessor will generally have no way of evaluating sizeof() on non-primitive types.  This may force the use of if() in some cases.

The compiler will ignore most syntax issues in code which is skipped in #if (some preprocessor-related issues can still cause trouble) but insist upon syntactic correctness for code skipped with if().  Thus, if code which is skipped for some builds but not others becomes invalid as a consequence of changes elsewhere in the file (e.g. renamed identifiers) it will generally squawk on all builds if it's disabled with if() but not if it's disabled by #if.  Depending upon why the code is being skipped, that may or may not be a good thing.

Some compilers will omit unreachable code while others won't; declarations of static storage duration within unreachable code, however, including string literals, may allocate space even if no code can ever use the space thus allocated.

Macros can use if() tests within them, but there is alas no mechanism for the preprocessor to perform any conditional logic within a macro [note that for use within macros, the ? : operator may often be better than if, but the same principles apply].

The #if directive can be used to control what macros get defined.

I think if() is often cleaner for most cases except those which involve making decisions based upon what compiler is using, or what macros should be defined; some of the above issues may necessitate using #if, however, even in cases where if would seem cleaner.


问:
Restrict cluster size with closed-source module in otherwise open-source program
I work in an academic research institute heavily dependent on high-performance computing. In the 10 years we have developed our own Fortran code which is very well regarded and can run on very large clusters. In order to have the larger research community benefit from the code, we are considering making it open-source. However, since our funding is highly dependent on the research we can perform with the code, we would be kind of shooting ourselves in the foot.

One of the ideas is to limit the number of CPUs the code can run on, e.g. maximum 1000 CPUs instead of the 100,000 we use. That way the global research community can benefit from the code, but we would be having an advantage on the size of the problems we can run.

Is such a feature conceptually possible? And how could such a feature be implemented?
Essentially we would like to open-source the complete code, but limit the parallelization (using MPI) to a fixed number of MPI threads, for example using a (closed-source) module.

答:
This can't really be done.

The idea behind open source is that the source is open, in other words, people will have access to it. From Wikipedia:

In production and development, open source as a development model promotes a universal access via a free license to a product's design or blueprint, and universal redistribution of that design or blueprint, including subsequent improvements to it by anyone.

By providing universal access to the design or blueprint, even if the released version is limited only to 1000 cores, it would be quite easy to simply change that number to 100000 or something.

Here are some options of what you could do instead:

Consider releasing the code under a license that restricts users of your code

This is difficult, in practice, because you can't really control if others follow the terms of your license when it leaves your hands

If you decide to go this route, consult a lawyer - Legal assistance is off topic on Programmers stack exchange

Release a closed source API library that allows other researchers to gain your functionality without having access to the code itself.


答:
You are trying to let the research commmunity benefit by having them be able to do what you do, without having them be able what you do. That sounds like you haven't really made a principled choice yet.

Software solutions like that in open source software aren't likely to work: the code is open source, after all. The first thing other institutions will do is rip out the closed source bit, replace it by an open source bit without such a limitation, and then everybody will use that.

There might be a compromise possible: don't open source the software, but sell licenses. Institutions with licenses also get the right to read and modify the code, but not to distribute it. Charge on a yearly basis. That way you can maybe make up for the loss in funding by taking some of theirs.

Another option is to release an older version, that you keep updated but always lagging behind by some number of years. However, an open source community might take up the project and develop new features faster than you do (or there might not; most people overestimate the interest others have in their software).

Or just release it and make use of the work others do on it. You'll always be the top experts on the software.

Title: Restrict cluster size with closed-source module in otherwise open-source program

Body:
I work in an academic research institute heavily dependent on high-performance computing. In the 10 years we have developed our own Fortran code which is very well regarded and can run on very large clusters. In order to have the larger research community benefit from the code, we are considering making it open-source. However, since our funding is highly dependent on the research we can perform with the code, we would be kind of shooting ourselves in the foot.

One of the ideas is to limit the number of CPUs the code can run on, e.g. maximum 1000 CPUs instead of the 100,000 we use. That way the global research community can benefit from the code, but we would be having an advantage on the size of the problems we can run.

Is such a feature conceptually possible? And how could such a feature be implemented?
Essentially we would like to open-source the complete code, but limit the parallelization (using MPI) to a fixed number of MPI threads, for example using a (closed-source) module.


答:
There is very little you can do to limit what others will do with your source code. They can make another module from scratch that can unlock the multiprocessing capability, or even improve it: it will cost time and expertise but if it is important to them, they will do it.

With ten years head start, you still have the opportunity to use your experience and knowledge of the code to continue to make the best research, even if you give others the source code that allows them to replicate your experiments. Your funders may even have more reason to go to you, as your research impact may be greater if you are leaders of an open source project that is used at several universities.

Instead of open source, you can try to restrict others legally, by publishing your source but putting proprietary restrictions on the source licence. I can think of several projects that have done this: Ghostscript, AT&T Unix, Microsoft .NET and Xerox PARC Smalltalk-80. While those ones eventually went fully open source, I expect that there are other less well-known ones that still place restrictions on how licensees use the source code. Of course, while publishing your source will mean those with less respect for the law may break the terms, it should keep bona fide academic researchers from running your code on
supercomputers as powerful as yours.


问:
Is it possible to "bake dimension into a type" in haskell?
Suppose I want to write a library that deals with vectors and matrices. Is it possible to bake the dimensions into the types, so that operations of incompatible dimensions generate an error at compile time?

For example I would like the signature of dot product to be something like

```<code>dotprod :: Num a, VecDim d => Vector a d -> Vector a d -> a
</code>```

where the d type contains a single integer value (representing the dimension of these Vectors).

I suppose this could be done by defining (by hand) a separate type for each integer, and group them in a type class called VecDim. Is there some mechanism to "generate" such types?

Or perhaps some better/simpler way of achieving the same thing?

答: That's called dependent typing.  Once you know the name, you can find more information on it than you ever could hope to want.  There's also an interesting haskell-like language called Idris that uses them natively.  Its author has done a few really good presentations on the topic that you can find on youtube.</p>


答:
In the java world, it is called Runnable.  In the C# world, it is called Action.

But, there is a better name which nicely fits within a larger view of things.

The larger view of things comes later, when you decide that besides your parameterless void functional interface you also need to have similar functional interfaces that accept one, two, or more arguments, or that return a value.  When that happens, you will want the names of all those entities to be isomorphic and correspondent with each other.

So, in Java, I have my own set of functional interfaces that I call Procedures, defined as follows:

```<code>public interface Procedure
{
    void invoke();
}

public interface Procedure1<T1>
{
    void invoke( T1 argument1 );
}
</code>```

... (you get the picture.)

And I also have a similar set of interfaces called Functions, defined in a similar way, with the first generic parameter being the return type:

```<code>public interface Function<R>
{
    R invoke();
}

public interface Function1<R,T1>
{
    R invoke( T1 argument1 );
}
</code>```

So, my point here is that Procedure is a very good name because it nicely fits within a larger view of things.  If you later decide to have similar functional interfaces with methods that accept arguments or return a value, you will run into this.

NOTE: I basically do agree with Karl Bielefeldt's assertion that "normal naming principles should [not] go out the window" and that "Interfaces should almost always be named after what they do, not after some generic syntactic idea."  But note that even he allows for "almost always".  Sometimes there is a need for (essentially anonymous) procedures and functions, and that's what the OP is asking, and that's what I am answering.

Amendment 2017-11-10:

You might ask, why Function1<R,T1> instead of Function1<T1,R>? It could go either way, but I have a preference for return values on the left because I like to follow the 'convert-from' (destination-from-source) naming convention as opposed to the 'convert-to' (source-to-destination) convention.  (Which is more of an accident than a convention, really, in the sense that most probably, nobody ever gave it any thought, because if they had given it any thought at all they would have arrived at the 'convert-from' convention.)

I read about this in Joel Spolksy - Making Wrong Code Look Wrong, it is a very long article, which I recommend reading in its entirety, but if you want to jump straight to the case at hand, search for 'TypeFromType', but to give you the TL;DR, the idea is that myint = intFromStr( mystr ) is much better than myint = strToInt( mystr ), because in the first case the names of the types are close to the associated values, so you can easily see that the 'int' matches with the 'int' and the 'str' matches with the 'str'.

So, by extension, I tend to order things in the way they are going to appear in code.

Body:
In the java world, it is called Runnable.  In the C# world, it is called Action.

But, there is a better name which nicely fits within a larger view of things.

The larger view of things comes later, when you decide that besides your parameterless void functional interface you also need to have similar functional interfaces that accept one, two, or more arguments, or that return a value.  When that happens, you will want the names of all those entities to be isomorphic and correspondent with each other.

So, in Java, I have my own set of functional interfaces that I call Procedures, defined as follows:

public interface Procedure
{
    void invoke();
}

public interface Procedure1<T1>
{
    void invoke( T1 argument1 );
}

... (you get the picture.)

And I also have a similar set of interfaces called Functions, defined in a similar way, with the first generic parameter being the return type:

public interface Function<R>
{
    R invoke();
}

public interface Function1<R,T1>
{
    R invoke( T1 argument1 );
}

So, my point here is that Procedure is a very good name because it nicely fits within a larger view of things.  If you later decide to have similar functional interfaces with methods that accept arguments or return a value, you will run into this.

NOTE: I basically do agree with Karl Bielefeldt's assertion that "normal naming principles should [not] go out the window" and that "Interfaces should almost always be named after what they do, not after some generic syntactic idea."  But note that even he allows for "almost always".  Sometimes there is a need for (essentially anonymous) procedures and functions, and that's what the OP is asking, and that's what I am answering.

Amendment 2017-11-10:

You might ask, why Function1<R,T1> instead of Function1<T1,R>? It could go either way, but I have a preference for return values on the left because I like to follow the 'convert-from' (destination-from-source) naming convention as opposed to the 'convert-to' (source-to-destination) convention.  (Which is more of an accident than a convention, really, in the sense that most probably, nobody ever gave it any thought, because if they had given it any thought at all they would have arrived at the 'convert-from' convention.)

I read about this in Joel Spolksy - Making Wrong Code Look Wrong, it is a very long article, which I recommend reading in its entirety, but if you want to jump straight to the case at hand, search for 'TypeFromType', but to give you the TL;DR, the idea is that myint = intFromStr( mystr ) is much better than myint = strToInt( mystr ), because in the first case the names of the types are close to the associated values, so you can easily see that the 'int' matches with the 'int' and the 'str' matches with the 'str'.

So, by extension, I tend to order things in the way they are going to appear in code.


问:
In WPF, should I base my converters on types or use-cases?
I'm looking for some advice on how to write my WPF value converters. The way I'm currently writing them, they are very specific, like (bool?,bool) => Brush, i.e. I'm writing each converter for a specific use case, in this case, the Brush is bound to an indicator showing equality information between the bool? and the bool. This obviously makes re-use very hard and I end up with a quite large list of converters. </p>

<p>Should I strive to write my converters in a more general way? Can I? </p>

答:
I solved this problem by writing a general purpose multiconverter that can take expressions and evaluate them, since it's a multibinding, it will update the value whenever one of the sources is updated, it also means I rarely have to write new converters at all. The only expense is the xaml verbosity. One example of an expression:

```<code><CheckBox Content="{Binding Role.Name_SV}">
    <CheckBox.Background>
         <MultiBinding Converter="{StaticResource ArithmeticsConverter}">
              <Binding Source="?"/>
              <Binding Source=">="/>
              <Binding Path="Included"/>
              <Binding Path="Requirement"/>
              <Binding>
                   <Binding.Source>
                        <SolidColorBrush>LightGreen</SolidColorBrush>
                   </Binding.Source>
              </Binding>
              <Binding>
                   <Binding.Source>
                        <SolidColorBrush>Red</SolidColorBrush>
                   </Binding.Source>
              </Binding>
         </MultiBinding>
     </CheckBox.Background>
 </CheckBox>
</code>```

The function here is that the checkbox background color is LightGreen if Included >= Requirement, and Red otherwise.

I guess some people will find this horrifyingly ugly, but I rather like how it lets me describe what I want without having to worry about when things are updated, it's more declarative and less imperative.

If anyone is interested I can post the source code for the converter.

Body:
I solved this problem by writing a general purpose multiconverter that can take expressions and evaluate them, since it's a multibinding, it will update the value whenever one of the sources is updated, it also means I rarely have to write new converters at all. The only expense is the xaml verbosity. One example of an expression:

<CheckBox Content="{Binding Role.Name_SV}">
    <CheckBox.Background>
         <MultiBinding Converter="{StaticResource ArithmeticsConverter}">
              <Binding Source="?"/>
              <Binding Source=">="/>
              <Binding Path="Included"/>
              <Binding Path="Requirement"/>
              <Binding>
                   <Binding.Source>
                        <SolidColorBrush>LightGreen</SolidColorBrush>
                   </Binding.Source>
              </Binding>
              <Binding>
                   <Binding.Source>
                        <SolidColorBrush>Red</SolidColorBrush>
                   </Binding.Source>
              </Binding>
         </MultiBinding>
     </CheckBox.Background>
 </CheckBox>

The function here is that the checkbox background color is LightGreen if Included >= Requirement, and Red otherwise.

I guess some people will find this horrifyingly ugly, but I rather like how it lets me describe what I want without having to worry about when things are updated, it's more declarative and less imperative.

If anyone is interested I can post the source code for the converter.


答:
I would say that it is the Single responsibility principle.

Even though it was first applied to Object Orientation, the underlying principle is valid even on non-OO environments - one thing, one job.

In object-oriented programming, the single responsibility principle
  states that every class should have responsibility over a single part
  of the functionality provided by the software, and that responsibility
  should be entirely encapsulated by the class. All its services should
  be narrowly aligned with that responsibility.

Title: What principle is violated by having a button do two radically different things or screens act radically different depending on the situation

Body:
I've come upon a situation several times in my career when previous developers have done something funny.

They will make a control (button) function radically different depending on how the screen was opened or some other condition in the data (e.g., save the data to a txt file vs. do a recalculation of something and store it in a database field). If you're lucky, they've changed the caption on the button when they change the functionality.

I've also seen them change the layout of the screen (hide controls, rename them, show entirely new sections). Again, likewise often they change the window caption.

This seems to be an anti-pattern because it make it hard for future developer to figure out what any one screen/control does without extensively walking the code and testing. And the temptation that they are falling for that they think they are saving the time to create a second form by creating one that works differently for different conditions.

What principle is being violated here? I know of the Single Responsibility Principle; but it doesn't seem to be a perfect fit. I think it's closer to "don't do this because it confuses the heck of the users", but I'm not sure if there is anything formal I can point to.


答:
First try to manipulate your data source to expose data in a way that matches your GUI better. Then you won't need as many converters in the first place. In the MVVM pattern the ViewModel is a representation of the Model which is better suited for binding by the view.

Then I would say try to create data-centric converters, where the converters are designed based on the data types of the input and output. Creating converters that are tailored for specific use-cases will just cause you to create lots of redundant converters.

Title: In WPF, should I base my converters on types or use-cases?

Body:
I'm looking for some advice on how to write my WPF value converters. The way I'm currently writing them, they are very specific, like (bool?,bool) => Brush, i.e. I'm writing each converter for a specific use case, in this case, the Brush is bound to an indicator showing equality information between the bool? and the bool. This obviously makes re-use very hard and I end up with a quite large list of converters. </p>

<p>Should I strive to write my converters in a more general way? Can I? </p>


问:
Python, namespace vs module with underscores
I'm developing a project that uses several independent modules, but all related to the same project.

However, I face this choice: module names with underscore vs. namespaces.

For example there is this tree:

```<code>Foo
 |-Bar1
 |  |-Bar2
 |-Foo1
 |  |-Foo2
 |  |-Foo3
</code>```

Let's say for example, that Foo3 depends on Bar2, but Foo2 and Bar2 are standalone.

What are the best practices regarding performance, and ease to package (to pypi) and code readability:

using _ : Foo_Bar_Bar1, Foo_Foo1_Foo2 and Foo_Foo1_Foo3

or using namespaces: Foo.Bar.Bar1, Foo.Foo1.Foo2 and Foo.Foo1.Foo3

It is more beautiful to use module and namespace, but on pip, independent packages are saved in different location. I've also read there is a bug when combining package installed from pypi and editable package that uses the same namespace

see also : https://github.com/pypa/pip/issues/3

Also, another problem about namespace is that Foo can't have any content and can't be a package (a namespace module must contain only a namespace declaration) like read here : https://pythonhosted.org/setuptools/setuptools.html#namespace-packages
(Or I didn't understand)

答:
I'd not be concerned about performance here, but about usability.

Modules are loaded just once in a Python program's lifetime. Referencing elements within modules and packages, including nested modules, is virtually free. Performance doesn't matter here.

Use modules to group your project into logical units; it is more readable and maintainable if things that are closely related conceptually are clustered within a namespace.


问:
HTTP Session: A single object or multiple?
I tested two approaches to store session data:

The classic: 1 key, 1 object (And every key as static final String in a class)

"user" --> UserObject

"preferences" --> List

...

An approach with only 1 object

"sessionObject" --> SessionObject

And my SessionObject contains UserObject and the list of preferences as attributes. This is a fairly simple example but imagine it with 20+ attributes.

The advantage I see in the second approach is that :

You only have to delete one key to ensure session is empty

You don't have to create the bothersome set of final static String to create the keys

You'll know what type of object to retrieve (Using key you have to cast)

Do you see any problem I might went over? Or does anything go against best practices?

答:
1 key, 1 object will be more predictable regarding interaction with app server and possible session replication techniques.  Not sure what you mean by "set of final static String" being necessary.  You may manage session keys any way you like.

Consider you have 20 preferences, and perhaps your preferences class has an enum of preference names.  Could get/set session a little bit indirectly:

```<code>class Preferences {

    private static final SESSION_KEY_PREFIX = Preferences.class.getName()+'.';

    enum Name {
        LOCALE,
        ...
    }

    static String get(HttpSession session, Name name) {
        return (String)session.getAttribute(SESSION_KEY_PREFIX + name.name());
    }

    static void set(HttpSession session, Name name, String value) {
        session.setAttribute(SESSION_KEY_PREFIX + name.name(), value);
    }

    static void clear(HttpSession session) {
        for(Name name : Name.values()) {
            session.removeAttribute(SESSION_KEY_PREFIX + name.name());
        }
    }
}
</code>```

You may then add preferences by just adding to the enum, and all specific interaction with the session is encapsulated.

This example pretty trivial so the Preferences class itself could also become an enum instead, without a separate "Name" enum.  Which could be:

```<code>enum Preference {
    LOCALE,
    ....;

    private final String sessionKey = Preference.class.getName()+'.'+name();

    String get(HttpSession session) {
        return (String)session.getAttribute(sessionKey);
    }

    void set(HttpSession session, String value) {
        session.setAttribute(sessionKey, value);
    }

    static void clear(HttpSession session) {
        for(Preference pref : Preference.values()) {
            session.removeAttribute(pref.sessionKey);
        }
    }
}
</code>```

Body:
1 key, 1 object will be more predictable regarding interaction with app server and possible session replication techniques.  Not sure what you mean by "set of final static String" being necessary.  You may manage session keys any way you like.

Consider you have 20 preferences, and perhaps your preferences class has an enum of preference names.  Could get/set session a little bit indirectly:

class Preferences {

    private static final SESSION_KEY_PREFIX = Preferences.class.getName()+'.';

    enum Name {
        LOCALE,
        ...
    }

    static String get(HttpSession session, Name name) {
        return (String)session.getAttribute(SESSION_KEY_PREFIX + name.name());
    }

    static void set(HttpSession session, Name name, String value) {
        session.setAttribute(SESSION_KEY_PREFIX + name.name(), value);
    }

    static void clear(HttpSession session) {
        for(Name name : Name.values()) {
            session.removeAttribute(SESSION_KEY_PREFIX + name.name());
        }
    }
}

You may then add preferences by just adding to the enum, and all specific interaction with the session is encapsulated.

This example pretty trivial so the Preferences class itself could also become an enum instead, without a separate "Name" enum.  Which could be:

enum Preference {
    LOCALE,
    ....;

    private final String sessionKey = Preference.class.getName()+'.'+name();

    String get(HttpSession session) {
        return (String)session.getAttribute(sessionKey);
    }

    void set(HttpSession session, String value) {
        session.setAttribute(sessionKey, value);
    }

    static void clear(HttpSession session) {
        for(Preference pref : Preference.values()) {
            session.removeAttribute(pref.sessionKey);
        }
    }
}


答:
A test fundamentally tells you, "If I supply input X to program P, I get output Y." Test driven development works by writing X and Y first then filling in the gap.

Work backwards. The program will produce some outputs. Whether these are control signals, images, web pages, text, lamps, toast, whatever: outputs. Produce some representative outputs by hand.

There will need to be some sort of data model for the system. This may be as trivial as a single number or a complex set of business objects or a complete numerical model of the atmosphere. This is where people deploy UML, BCNF and so on. You can't avoid reasoning about the data model, but you can relate it to your output examples. "Output X1 is seen when the data model contains D1". So you end up writing a set of output formatters and postprocessors from their tests.

https://softwareengineering.stackexchange.com/questions/244451/relationship-between-tdd-and-software-architecture-design?lq=1  : TDD is a methodology and a means of organising the work of program production. You have to do something first, and in TDD that is write a test. It doesn't absolve you from needing to do architecture.

Title: Filling the gap between Conception and Unit Test

Body:
I am stuck trying to do TDD. I'd rather seek the counsel of others who have gone before rather than waste time with trial and error.

QUESTION:

What diagrams / exercises / development processes can I insert between "foggy notion of what system is supposed to do" (aka Conception) and "Write Test"?

Anything else included in this question is simply additional information to help communicate / clarify my question; not to change the question in any way. I do not care what diagrams / exercises / development processes I use, as long as they get me unstuck.

When I say Conception I just mean a foggy informal mental-only notion of what a system should / can / will / might do.

FORM OF ANSWER:

I'm trying to navigate from conception to Unit Test in my development process. I'm looking for a way, a path, a road map, a bridge. An answer might look something like this:

do a xyxyx type diagram to get the aaaas, then take all the
  aaaas and do a wywywyw diagram, then all the ccccs on the
  wywywyw diagram will be the classes you need to unit test and the
  lllllls will be the scenarios of the tests.

PROBLEM BACKGROUND:

I found a TDD flowchart and converted it to a Google Drawing. I'm using NUnit. I have studied TDD, know what it is and practiced it somewhat. This flow chart is for TDD only; no steps before Unit Testing are included.

The flowchart starts out with "Write Test". I had my concept, nothing I had read said I needed anything else first, so I tried following the flow chart. It was too much of a leap to go from "foggy notion" to Unit Test. This caused me "designer's block". Then I read someone say "just do it!" I tried that, but the resulting tests and ensuing code wandered somewhat aimlessly since there was nothing to guide what tests to write.

ATTEMPTS AT SOLUTION:

Some ideas I have explored already that seem helpful (but the question is not about these things):

BDD (I used SpecFlow)

use case diagrams

SpecFlow starts with a verbal description of a "feature" and creates tests that NUnit can run; they don't look like the unit tests I created manually but maybe I'll figure out how they relate to one another.

Use cases helped me get convert the initial foggy notion into a formal description, which was a bit of sunshine. I used Visual Studio 2013 for that. I don't see any facility (in Visual Studio at least) to convert my use case into Unit Tests, although I found some evidence that this is one purpose of a use case. Quoting from the UML User Guide, 2nd ed., p.246:

A use case diagram can be forward engineered to form tests for the
  element to which it applies.

And it looks like Visual Studio maybe wants to convert it because it can store template data on the use case and has "Code Generation Settings"

Here is a picture of what I have tried so far


答:
Two things could help you there:

Instead of Use Cases, User Stories. Why? Well User Stories are written for/by the user. They are not an accurate description of functionality, but do specify what the user wants to do. This can be your initial road map into writing code that actually allows the user to do something, rather than comply with system specification.

A class diagram. Once you understand the functionality you want to code, you have to create the model you'll be using. This doesn't have to be complete, or extensive; the idea is that you'll define your design (and what classes you need) while doing your tests (this is why TDD is 'design'), but you need to know what classes you need, the properties they have, etc.

If you're working with small user stories (as they usually are), your class diagram is going to be small. So it is really more that you need the 'idea' of what classes you'll be needing.


问:
Is CORBA outdated?
I'm just learning about midleware in class, and our teacher has told us about CORBA. Doing a bit of research, I've found that the last version (CORBA 3) was released in 2002, which seems quite old in the computers science (well, in fact I know there is also CORBA 3.3, released in 2012, but..)

So there's my question: is CORBA outdated?

Update: to make it less subjective, let's try asking some particular things:

Is being CORBA used in large new projects?

Does CORBA have known difficulties that makes it useless in that scene?

Are there new frameworks rising to fill its place?

I think all this fits quite well with the original question (and have been already answered)

Thanks in advance

答:
Yes, CORBA is rarely specified for new systems. But, there are plenty of live systems that you might want or need to connect to using their CORBA interface, as it was very popular from the early 1990s, for about twenty years, and live systems often last many decades.

@Blrfl shared a link to The rise and fall of CORBA (Michi Henning, 2006, ACM Queue magazine) which backs up my assertion.

During its lifetime, CORBA has moved from being a bleeding-edge technology for early adopters, to being a popular middleware, to being a niche technology that exists in relative obscurity. ... CORBA’s history is one that the computing industry has seen many times, and it seems likely that current middleware efforts, specifically Web services, will reenact a similar history.)

Title: Is CORBA outdated?


答:
The short: Yes, sadly(*), CORBA is outdated, as in:

No decent .NET implementation

The existing C++ binding is ugly, although there does exist a new C++11 binding

No decent implementations for other modern languages (except Python)

That being said, existing CORBA implementations like omniORB, TAO, R2CORBA are supported and used, and are IMHO much more mature than many other IPC/RPC frameworks, although these are certainly more "modern" and are probably the future.

(*) I write sadly, and it is indeed a sad affair, because (point 3 from Q), there are quite a few frameworks rising, but there's not one that can fully replace it at the moment, and they all have problems of their own. (Immaturity, tailored for a narrow usecase set, interoperability (e.g. WCF via net.tcp), performance, footprint, licensing (ICE), ...)

Additionally, addressing point 2., while I do not agree with some points in The Rise and Fall of CORBA, one point that is indeed today a pain point is the lack of good versioning, quoting:

Versioning.

Deployed commercial software requires middleware that
  allows for gradual upgrades of the software in a backward-compatible
  way. CORBA does not provide any such versioning mechanism (other than
  versioning by derivation, which is utterly inadequate). Instead,
  versioning a CORBA application generally breaks the on-the-wire
  contract between client and server. This forces all parts of a
  deployed application to be replaced at once, which is typically
  infeasible. (...)

While it is not as horrible as the paragraph makes it sound, it is an issue for which I do not know of an elegant solution, even when sticking to a single CORBA implementation for all your parts.

Title: Is CORBA outdated?

Body:
I'm just learning about midleware in class, and our teacher has told us about CORBA. Doing a bit of research, I've found that the last version (CORBA 3) was released in 2002, which seems quite old in the computers science (well, in fact I know there is also CORBA 3.3, released in 2012, but..)

So there's my question: is CORBA outdated?

Update: to make it less subjective, let's try asking some particular things:

Is being CORBA used in large new projects?

Does CORBA have known difficulties that makes it useless in that scene?

Are there new frameworks rising to fill its place?

I think all this fits quite well with the original question (and have been already answered)

Thanks in advance


问:
What are the real benefits of static code analysis?
Tools like pc-lint or QAC can be used to perform static code analysis on a code base.

In my experience the static analysis often yields a huge amount of noise, i.e. warnings on things that are not real bugs but somehow violate one of the rules in a given rule set. Turning off certain rules (either for good in the rule set or via special comments in the code) can be a real cumbersome process.

What are the real benefits of static code analysis?

答: When starting out with a new language it's nice to have a coach. That's how I think of static analysis tools. I write a lot of javascript and in the beginning I picked up a few bad habits mainly because I was transferring some things from earlier languages. Javascript is pretty flexible so you can get away with pretty much anything but if I'd had jslint warning me about certain patterns I would have picked up better coding patterns right from the beginning instead of having to relearn stuff later on.</p>


问:
Storm topology to handle "dating website"-like workloads
suppose im writing a dating website, similar to okcupid. there are profiles, and i need to compute the (N^2) "match" table - given every 2 profiles whats the match between them?

I was thinking this could be done by creating a spout to listen on a "new/updated profiles" queue (say kafka, doesnt matter), but then how do I break down the matching to achieve any degree of parallelism?

If I have a single bolt that compares the profile vs the entire DB that wont scale.

If I create another spout, for "all profiles" it will run in a continous loop and never stop (?)

Obviously the assumption is that the "churn rate" (rate of new/updated profiles) is less of an issue than the sheer size of the database.

Any suggestions on how to design the topology would be very welcome.

答:
Although I have not worked in this area, it seems like this is the type of problem one would use something like Apache Giraph to handle. You essentially want a huge population of "things" which you suspect are "related" to each other possibly across a large number of dimensions, and you want to pair them up optimally based on the strongest matches.

You don't want to hard code what those things are, the possible dimensions they may be related, and the rules that define each relationship. Not only would that be a lot of work, it wouldn't scale well.

This link is a proprietary graph product, but does a good job showing how a graph data model would apply to online dating. Same concept could be done with Apache Giraph, or any other graph computational tool:

https://linkurio.us/recommendation-and-graphs-an-online-dating-use-case/


问:
What is the preferred way to approach this problem in object-oriented design? - virtual disks abstraction
I am writing a program that manipulates encrypted virtual disks and encrypted flash drives (eg. importing disks into my application, mounting/unmounting, changing passwords etc.). I am still new to object-oriented design so I have run into the following problem.

I have identified three disk types:

Disk stored in a file (virtual disk) on a hard-drive (fixed location)

Disk stored in a file (virtual disk) on a removable device (eg. flash drive, absolute path can change)

Encrypted flash drive (same as above but stored directly on the device so no filepath)

The operations i need to do over these disks are mounting, unmounting, checking for presence on the computer and changing password. The main problem i have is with the differences (and similarities) in storing their location (file on a hard-drive can do with only an absolute filepath; encrypted device can do with a device ID; file on a removable device needs both device ID and a relative path on the device).

I have came up with multiple solutions so far but none of which I liked. Is there a preferred way to do this? Or am I thinking about this the wrong way?

Edit: The solutions I came up with so far:

Solution 1:

Creating an abstract base Disk class with abstract methods for the operations i need (and some data about mounting which is common to all disks).

From the base class I derive a PhysicalDisk class and a VirtualDisk class. VirtualDisk stores its location as a fixed path (string) and PhysicalDisk stores its location in a RemovableDevice class (contains a device ID, status flags etc.). Both classes implement the operations from the base class with respect to how their location is stored.

From the VirtualDisk class i then derive a RemovableVirtualDisk class, which adds a RemovableDevice class as a member and reimplements some of the parent methods to account for this change.

The problem is that the implemented methods in derived classes are very similar, varying mostly in respect to how the location of the disk is stored.

Solution 2:

Creating one class for all disk types, eg. EncryptedDisk, which then stores the disk location using polymorphism, in an abstract DiskLocation class. From DiskLocation I derive a FileOnFixedDevice class (for virtual disks) and a RemovableDevice class (for encrypted drives). From that i further derive a FileOnRemovableDevice class (for virtual disks on removable drives).

The classes implement a GetSystemLocation() method and a IsDeviceInSystem() method, which are then used uniformly in the EncryptedDisk class for all disk types.

The problem I had with this solution is that I perform checks for device availability even when it does not make sense (disks on hard-drives). Also I might need to have some specific information about the disk location in the future, not just polymorphic objects which could be anything.

Maybe the optimal design is somewhere in the middle? Or would some different approach solve my problems?

答:
The problem is that the implemented methods in derived classes are
  very similar, varying mostly in respect to how the location of the
  disk is stored.

This is not a problem.  The point of object-oriented design is not to reduce the total amount of code by factoring common code into superclass methods.  The point of object oriented design is proper modelling of the real-world entities.  So, it is perfectly fine that many of the methods are very similar.

If you can think of ways in which you can factor common code out of the derived classes and into new methods of the superclass, do that only if the superclass methods have well defined purposes that actually make sense for the superclass when examined on its own, without any knowledge of its subclasses.

Both of the approaches that you described look sound, so I do not know which one of them you should prefer, but whatever you do, try to keep the total number of classes (and the total amount of code, if possible) you need to represent your model as small as possible, because it is quite likely to change as you gain a better understanding of the situation, so the smaller it is, the easier it will be to change it.

In light of that, the first approach might be preferable, because it looks smaller.


问:
How come the computer doesn't have to read the entire table when the column is indexed?
Let's say a table with two columns has 100 quadrillion records. And I want to find a record that has column #2 equal something.

If column #2 is indexed it returns the result immediately, but if it's not the computer has to read the entire table so it takes a long time.

How come the computer doesn't have to read the entire table when the column is indexed? How does it know what the result is without reading the table?

答:
Basically, because an index is ordered, and when searching through an ordered data set, you don't have to search every item to find the element you're looking for; there are faster ways.

Discussing database indexing in detail can become very arcane very quickly, but the simplest way to answer this is that you can use techniques such as a binary search to find the element much more quickly, for reasons that should be intuitively obvious to anyone who's ever played the "I'm thinking of a number between 1 and 100" guessing game.  You know how you can always guess the number within 7 guesses, not 100, if your guesses cut the size of the number of values to be "searched" in half each time?  Databases do something very similar with indexing.


答:
It is not that the computer knows what the result is without reading the table.  It actually does quite a lot of work to find the result, but it is very fast, so it appears instantaneous to you.  But yes, certainly, it does not read the entire table.

The way it works is implementation dependent, but a popular simple algorithm which serves for illustration purposes is binary search.  It works similarly to how you find a word in a dictionary. Clearly, you don't read the entire dictionary every time you are looking for a word, do you?

What you do is that you open up the dictionary somewhere near the middle, (the algorithm will go to the exact middle, but that's just computers finding precision easier than approximation,) then you read just one word from that page, and see whether the word you are looking for comes before or after the word you read.  If it comes before, you ignore the second half of the book, and focus only on the first half; if it comes after, you ignore the first half of the book, and you focus only on the second half: then you open up the page in the middle of the half that you are focusing on, read another word, see if your word comes before or after, and keep repeating these steps, until you have found the right page.

The reason why this works is because the words in the dictionary are sorted.  If they were not sorted, we would have to go through the entire dictionary to find a word.  What an index does on a database is that it provides a sorted view of the data, so that binary search can be used to find a value.

Using binary search you can find the right page for any word in a thousand-page dictionary with just 10 page lookups, and you can find the right page for any word in a 4-billion page dictionary with just 32 page lookups. As you see, it scales non-linearly, to our advantage, which is sweet.

Body:
Let's say a table with two columns has 100 quadrillion records. And I want to find a record that has column #2 equal something.

If column #2 is indexed it returns the result immediately, but if it's not the computer has to read the entire table so it takes a long time.

How come the computer doesn't have to read the entire table when the column is indexed? How does it know what the result is without reading the table?