答:
Seconding JBRWilkinson in the suggestion to drop the structs.

Beyond what was written in that answer, having a struct implement IUpdateable implies the struct needs must be mutable, which can invite a certain class of bug.  Structs, being on the heap, are assigned by copy not by reference, so any change made to a copy will not be reflected back into your database of game objects.  I.e.  if you write code like

```<code>    foreach (var particle in SomeParticleCollection)
    {
        particle.EnabledChanged += myEvent;
    }
</code>```

it may actually do nothing, because the struct "particle" will be a copy of the struct in the collection.  Similarly, anybody implementing an IParticleEffect that changes the incoming IParticle will be disappointed despite it having been passed by reference.

(I suspect that if any system uses mutable structs to implement IUpdateable, they actually keep them boxed most of the time.  This would seem defeat the purpose of the optimization, unless I'm missing something.)

For more, see  here and, maybe, here

Body:
Seconding JBRWilkinson in the suggestion to drop the structs.

Beyond what was written in that answer, having a struct implement IUpdateable implies the struct needs must be mutable, which can invite a certain class of bug.  Structs, being on the heap, are assigned by copy not by reference, so any change made to a copy will not be reflected back into your database of game objects.  I.e.  if you write code like

    foreach (var particle in SomeParticleCollection)
    {
        particle.EnabledChanged += myEvent;
    }

it may actually do nothing, because the struct "particle" will be a copy of the struct in the collection.  Similarly, anybody implementing an IParticleEffect that changes the incoming IParticle will be disappointed despite it having been passed by reference.

(I suspect that if any system uses mutable structs to implement IUpdateable, they actually keep them boxed most of the time.  This would seem defeat the purpose of the optimization, unless I'm missing something.)

For more, see  here and, maybe, here


问:
Is it better to draw my own graphics or import images?
I am about to start a Tetris clone using Java as my programming language. While I was designing how it'd be done, I've stumbled upon this question:

What would be better, if any difference at all, regarding performance 1, to draw my game?

For a matter of simplicity, I will use a background grid as an example. The following code will be running in the graphics update loop:

1) To perform the drawing using my graphics g variable, such as this

```<code>g.setColor(Color.DARK_GRAY);
for(int x = 0; x < COL_COUNT; x++) {
    for(int y = 0; y < VISIBLE_ROW_COUNT; y++) {
        g.drawLine(0, y * TILE_SIZE, COL_COUNT * TILE_SIZE, y * TILE_SIZE);
        g.drawLine(x * TILE_SIZE, 0, x * TILE_SIZE, VISIBLE_ROW_COUNT * TILE_SIZE);
    }
}
</code>```

or

2) pre-load an image like this:

```<code>BufferedImage img = null;
try {
    img = ImageIO.read(new File("grid.jpg"));
} catch (IOException e) {
}
</code>```

and then use my graphics to draw it using Graphics drawImage:

```<code>g.drawImage(img, x, y, null)
</code>```

1 - I know that a Tetris game isn't that performance-hungry, but I believe that this doesn't invalidate the question.

答:
You already have both alternatives, so what is stopping you from running 1000 times each one of them and checking the average times for each? Then, after that, it is just a matter of picking up the fastest one.

Once you are done with your tests, update your question and let us know.

ContentLicense: CC BY-SA 3.0


问:
Are error variables an anti-pattern or good design?
In order to handle several possible errors that shouldn't halt execution, I have an error variable that clients can check and use to throw exceptions. Is this an Anti-Pattern? Is there a better way to handle this? For an example of this in action you can see PHP's mysqli API. Assume that visibility problems (accessors, public and private scope, is the variable in a class or global?) are handled correctly.

答:
The question is already answered, but I can't help myself.

You can't really expect Exception to provide a solution for all use cases. Hammer anyone?

There are cases where Exceptions are not the end all and be all, for example, if a method receives a request and is responsible for validating all the fields passed, and not only the first one then you have to think that it should be possible to indicate the cause of the error for more than one fields. It should be possible to also indicate if the nature of the validation prevents the user from going further or not. An example of that would be a not strong password. You could show a message to the user indicating that the entered password is not very strong, but that it is strong enough.

You could argue that all of these validations could be thrown as an exception at the end of the validation module, but they would be error codes in anything but in the name.

So the lesson here is: Exceptions have their places, as do error codes. Chose wisely.


答:
Consider drawing it in code, but only draw it once and cache it.

When you procedurally draw the same, static graphic every frame, you shouldn't generate it again and again using the same for-loops. Draw it once to a buffered image, and then paste that image each frame.

That way the decision between procedurally creating a graphic and loading it from a file just becomes a question of development-time (what's faster - drawing it in a graphic editor or writing the code to draw it?), loading-time (what's faster - loading and decoding a graphics file or running the code to draw the image?). The answers to these two question vary greatly on the nature of the image and your skills as a graphic artist or programmer.

A third aspect is filesize. In most cases, the executable code required to generate an image will be smaller than the encoded image file, so you can often reduce the total size of the application by generating assests procedurally. Nowadays application size does not matter much for a desktop application. But there are at least two cases where every kB counts: Smartphone apps (users will be reluctant to download a large app when they have a limited data plan) and web applications (every second of additional loading time causes more users to lose patience and close the tab).

Title: Is it better to draw my own graphics or import images?

Body:
I am about to start a Tetris clone using Java as my programming language. While I was designing how it'd be done, I've stumbled upon this question:

What would be better, if any difference at all, regarding performance 1, to draw my game?

For a matter of simplicity, I will use a background grid as an example. The following code will be running in the graphics update loop:

1) To perform the drawing using my graphics g variable, such as this

```<code>g.setColor(Color.DARK_GRAY);
for(int x = 0; x < COL_COUNT; x++) {
    for(int y = 0; y < VISIBLE_ROW_COUNT; y++) {
        g.drawLine(0, y * TILE_SIZE, COL_COUNT * TILE_SIZE, y * TILE_SIZE);
        g.drawLine(x * TILE_SIZE, 0, x * TILE_SIZE, VISIBLE_ROW_COUNT * TILE_SIZE);
    }
}
</code>```

or

2) pre-load an image like this:

```<code>BufferedImage img = null;
try {
    img = ImageIO.read(new File("grid.jpg"));
} catch (IOException e) {
}
</code>```

and then use my graphics to draw it using Graphics drawImage:

```<code>g.drawImage(img, x, y, null)
</code>```

1 - I know that a Tetris game isn't that performance-hungry, but I believe that this doesn't invalidate the question.


答:
There are multiple ways to signal an error:

an error variable to check: C, Go, ...

an exception: Java, C#, ...

a "condition" handler: Lisp (only ?), ...

a polymorphic return: Haskell, ML, Rust, ...

The problem of the error variable is that it is easy to forget to check.

The problem of exceptions is that is creates hidden paths of executions, and, although try/catch is easy to write, ensuring a proper recovery in the catch clause is really difficult to pull off (no support from type systems/compilers).

The problem of condition handlers is that they do not compose well: if you have dynamic code execution (virtual functions), then it is impossible to predict which conditions should be handled. Furthermore, if the same condition can be raised in several spots, there is no telling that a uniform solution can be applied each time, and it quickly becomes messy.

Polymorphic returns (Either a b in Haskell) are my favorite solution so far:

explicit: no hidden path of execution

explicit: fully documented in function type signature (no surprises)

hard to ignore: you have to pattern match to get the desired result out, and handle the error case

The only issue is that they may potentially lead to excessive checking; the languages that use them have idioms to chain the calls of functions that use them, but it may still require a bit more typing/clutter. In Haskell this would be monads; however, this is far scarier than it sounds, see Railway Oriented Programming.

Title: Are error variables an anti-pattern or good design?

Body: In order to handle several possible errors that shouldn't halt execution, I have an error variable that clients can check and use to throw exceptions. Is this an Anti-Pattern? Is there a better way to handle this? For an example of this in action you can see PHP's mysqli API. Assume that visibility problems (accessors, public and private scope, is the variable in a class or global?) are handled correctly.

ContentLicense: CC BY-SA 4.0


问:
Circular dependency and object creation when attempting DDD
I have a domain where an Organization has People.

Organization Entity

```<code>public class Organization {
    private readonly List<Person> _people = new List<Person>();

    public Person CreatePerson(string name) {
        var person = new Person(organization, name);
        _people.Add(person);
        return person;
    }

    public IEnumerable<Person> People {
        get { return _people; }
    }
}
</code>```

Person Entity

```<code>public class Person
{
    public Person(Organization organization, string name) {
        if (organization == null) {
            throw new ArgumentNullException("organization");
        }

        Organization = organization;
        Name = name;
    }

    public Organization { get; private set; }
    public Name { get; private set; }
}
</code>```

The rule for this relationship is that a Person must belong to exactly one Organization.

The invariants I want to guarantee are:

A person must have an organization

this is enforced via the Person's constuctor

An organization must know of its people

this is why the Organization has a CreatePerson method

A person must belong to only one organization

this is why the organization's people list is not publicly mutable (ignoring the casting to List, maybe ToEnumerable can enforce that, not too concerned about it though)

What I want out of this is that if a person is created, that the organization knows about its creation.

However, the problem with the model currently is that you are able to create a person without ever adding it to the organizations collection.

Here's a failing unit-test to describe my problem

```<code>[Test]
public void AnOrganizationMustKnowOfItsPeople()
{
    var organization = new Organization();
    var person = new Person(organization, "Steve McQueen");

    CollectionAssert.Contains(organization.People, person);
}
</code>```

What is the most idiomatic way to enforce the invariants and the circular relationship?

答:
You can guarantee that the bi-directional association between the Person and Organization objects cannot be broken by code outside the classes themselves by using events:

```<code>public class PersonCreatedEventArgs : EventArgs
{
    public readonly Person Person;
    public readonly Organization Organization;

    public PersonCreatedEventArgs(Person person, Organization organization)
    {
        this.Organization = organization;
        this.Person = person;
    }
}

public class Person
{
    public static event EventHandler<PersonCreatedEventArgs> PersonAdded;
    public static event EventHandler<PersonCreatedEventArgs> PersonRemoved;

    private Organization organization;
    private string name;

    public string Name { get { return name; } private set { name = value; }}

    public Organization Organization {
        get {
            return organization;
        }
        set {
            if (organization == value)
                return;
            if (organization != null && PersonRemoved != null)
                PersonRemoved(this, new PersonCreatedEventArgs(this, organization));
            organization = value;
            if (organization != null && PersonAdded != null)
                PersonAdded(this, new PersonCreatedEventArgs(this, organization));
        }
    }

    public Person(Organization organization, string name)
    {
        if (organization == null)
        {
            throw new ArgumentNullException("organization");
        }

        Name = name;
        Organization = organization;
    }
}

public class Organization
{
    static Organization()
    {
        Person.PersonAdded += Person_PersonAdded;
        Person.PersonRemoved += Person_PersonRemoved;
    }

    static void Person_PersonRemoved(object sender, PersonCreatedEventArgs e)
    {
        e.Organization._people.Remove(e.Person);
    }

    static void Person_PersonAdded(object sender, PersonCreatedEventArgs e)
    {
        e.Organization._people.Add(e.Person);
    }

    private readonly List<Person> _people = new List<Person>();

    public IEnumerable<Person> People
    {
        get { return _people.AsReadOnly(); }
    }
}
</code>```

In this scheme, setting the Organization of a Person fires events notifying the Organization of the association.

Since the "PersonRemoved" and "PersonAdded" events can only be fired from within the Person class itself, a Person can only be constructed with a given Organization, and the "People" list is returned read-only, all code outside the two classes is prevented from damaging the bi-directional association.   In practice you'll want to add some asserts in the events to make sure the data stays consistent (in case somebody does something nasty with reflection, or in case of serialization errors, or etc.)

Body:
You can guarantee that the bi-directional association between the Person and Organization objects cannot be broken by code outside the classes themselves by using events:

public class PersonCreatedEventArgs : EventArgs
{
    public readonly Person Person;
    public readonly Organization Organization;

    public PersonCreatedEventArgs(Person person, Organization organization)
    {
        this.Organization = organization;
        this.Person = person;
    }
}

public class Person
{
    public static event EventHandler<PersonCreatedEventArgs> PersonAdded;
    public static event EventHandler<PersonCreatedEventArgs> PersonRemoved;

    private Organization organization;
    private string name;

    public string Name { get { return name; } private set { name = value; }}

    public Organization Organization {
        get {
            return organization;
        }
        set {
            if (organization == value)
                return;
            if (organization != null && PersonRemoved != null)
                PersonRemoved(this, new PersonCreatedEventArgs(this, organization));
            organization = value;
            if (organization != null && PersonAdded != null)
                PersonAdded(this, new PersonCreatedEventArgs(this, organization));
        }
    }

    public Person(Organization organization, string name)
    {
        if (organization == null)
        {
            throw new ArgumentNullException("organization");
        }

        Name = name;
        Organization = organization;
    }
}

public class Organization
{
    static Organization()
    {
        Person.PersonAdded += Person_PersonAdded;
        Person.PersonRemoved += Person_PersonRemoved;
    }

    static void Person_PersonRemoved(object sender, PersonCreatedEventArgs e)
    {
        e.Organization._people.Remove(e.Person);
    }

    static void Person_PersonAdded(object sender, PersonCreatedEventArgs e)
    {
        e.Organization._people.Add(e.Person);
    }

    private readonly List<Person> _people = new List<Person>();

    public IEnumerable<Person> People
    {
        get { return _people.AsReadOnly(); }
    }
}

In this scheme, setting the Organization of a Person fires events notifying the Organization of the association.

Since the "PersonRemoved" and "PersonAdded" events can only be fired from within the Person class itself, a Person can only be constructed with a given Organization, and the "People" list is returned read-only, all code outside the two classes is prevented from damaging the bi-directional association.   In practice you'll want to add some asserts in the events to make sure the data stays consistent (in case somebody does something nasty with reflection, or in case of serialization errors, or etc.)


问:
How to transition from "help vampire" to "developer"?
I've been a computer enthusiast my entire life, but didn't first start programming (web development) until I began College. It is now four years later - I am about to graduate, have had a handful of full-time internships and part-time work, all revolving around web dev... But I still find myself more often than not seeking out help, tutorials or stackexchange answers to my questions instead of working out problems entirely on my own.

I hear the term "help vampire" -- someone who asks/seeks help with their problems rather than work through issues themselves -- and while that isn't true for me a hundred percent, I find my threshold of getting "frustrated" when trying to accomplish something is quite low and it doesn't take long once I've found a problem to start searching online for a solution, as opposed to work one out myself.

I am certainly able to do my work, but I want to know how I can actually learn to THINK and REMEMBER like a developer, as opposed to relying on online answers as a crutch. It's a nasty habit and I really feel like it's limiting my development potential, speed, flexibility and adaptation to new languages/environments.

TL;DR: How did you transition from seeking help (whether in the form of Q&A's, plugins, tutorials, code-inspecting, etc) to developing solutions (answering the Q&A's, writing your own plugins, creating the tutorials, etc)?

答:
I think you got the definition of a help vampire wrong. A help vampire make people work for them. Reading a solution online does not consume anyone's time. It is just a way to use an available resource. Knowing when to ask a team member for basic help when no documentation is available is something harder to balance.

When working on something you don't know well, you should try to find a solution AND look for existing solution. In which order?

trying yourself first is a way to train your analysis skills. It also avoids tunneling your design space around existing architecture

reading about existing solutions allows you to benefit from the work and experience of the "wiser" programmers who provided those solutions. It helps you to avoid basic mistakes and to reinvent wheels

I have found that I get the best result when I try to build my own design and regularly check existing solutions and compare them to my work. However this method takes a lot of time. It is a good way to learn about something new. But if your boss wants you to ship in two weeks, it might not be the right way.

If you are facing tight schedule a want to limit the risk, spending more time on existing solution and less time on a new design may be a safer choice.

Ignoring free online resources about how people solves problems is as much a sin as only relying on other people's work.


问:
Is there such a thing as API documentation management?
So I started thinking, what is the best practice for publishing generated documentation (e.g. Doxygen, NaturalDocs, etc.) in terms of infrastructure?

I would be generating it through continuous integration:

Should it be put in a regular web server?, or should I use something like Sharepoint or some other content publishing software?

Should the documentation be available for each build?, or just stable releases

Should I put a full copy of each documentation iteration?, or should I put  it in version control overwriting itself? (a repository separate to the project code, of course)

For some weird reason I find hard to think that I should just put it in a web enabled server, but this is how I see most do it:

http://docs.spring.io/spring/docs/

However, what happens when your company works on tenths if not hundreds of projects?, most documentation generation tools AFAIK just give you the final HTML output, but it is up to you to manage it.

So, what gives?, is there a better practice/solution than just putting it in the "doc server"?

答:
That's right - document tools that produce HTML should be put on a webserver. If you have many projects, just copy the html output into subdirectories and update a master index page that links to each one. You can put a link to each project's html 'start page' in a wiki for each project (if you use a project management site like redmine or trac).

The point is to create a quick and easy to access link to this documentation. If you put it in sharepoint and make it a downloadable resource that has to be signed-in to and unzipped and then bookmarked by the individual - you can expect to find most people won't bother. If its just another bookmark in their browser, you can expect many people to view it, and getting it viewed is why you do it in the first place.

Personally, I'd keep revisions for old stable versions only. Builds are very transitory, though you will have to keep a "current" or "latest" version that is always overwritten with the current build. If its generated, there's no point in storing the output as well. You could, if you store the binaries just so you don't have to re-generate it, but you only do that for final releases.


问:
Quadtree with duplicates
I'm implementing a quadtree. For those who don't know this data structure, I am including the following small description:

A Quadtree is a data structure and is in the Euclidean plane
  what an Octree is in a 3-dimensional space. A common use of quadtrees
  is spatial indexing.

To summarize how they work, a quadtree is a collection — let's say of
  rectangles here — with a maximum capacity and an initial bounding box. When trying to insert an element into
  a quadtree which has reached its maximal capacity, the quadtree is
  subdivided into 4 quadtrees (a geometric representation of which will
  have a four times smaller area than the tree before insertion); each
  element is redistributed in the subtrees according to its position,
  ie. the top left bound when working with rectangles.

So a quadtree is either a leaf and has less elements than its capacity, or a tree with 4 quadtrees as children (usually north-west, north-east, south-west, south-east).

My concern is that if you try to add duplicates, may it be the same element several times or several different elements with the same position, quadtrees have a fundamental problem with handling the edges.

For instance, if you work with a quadtree with a capacity of 1 and the unit rectangle as the bounding box:

```<code>[(0,0),(0,1),(1,1),(1,0)]
</code>```

And you try inserting twice a rectangle the upper-left bound of which is the origin:
(or similarly if you try inserting it N+1 times in a quadtree with a capacity of N>1)

```<code>quadtree->insert(0.0, 0.0, 0.1, 0.1)
quadtree->insert(0.0, 0.0, 0.1, 0.1)
</code>```

The first insert will not be a problem:

But then the first insert will trigger a subdivision (because the capacity is 1):

Both rectangles are thus put in the same subtree.

Then again, the two elements will arrive in the same quadtree and trigger a subdivison…

And so on, and so forth, the subdivision method will run indefinitely because (0, 0) will always be in the same subtree out of the four created, meaning an infinite recursion problem occurs.

Is it possible to have a quadtree with duplicates? (If not, one may implement it as a Set)

How can we solve this problem without breaking completely the architecture of a quadtree?

答:
I think there is a misapprehension here.

As I understand it, every quadtree node contains a value indexed by a point. In other words, it contains the triple (x,y,value).

It also contains 4 pointers to child nodes, which may be null. There is an algorithmic relationship between the keys and the child links.

Your inserts should look like this.

```<code>quadtree->insert(0.0, 0.0, value1)
quadtree->insert(0.0, 0.0, value2)
</code>```

The first insert creates a (parent) node and inserts a value into it.

The second insert creates a child node, links to it, and inserts a value into it (which may happen to be the same as the first value).

Which child node is instantiated depends on the algorithm. If the algorithm is in the form [x) and the coordinate space lies in the range [0,1) then each child will span the range [0,0.5) and the point will be placed in the NW child.

I see no infinite recursion.

Title: Quadtree with duplicates

Body:
I think there is a misapprehension here.

As I understand it, every quadtree node contains a value indexed by a point. In other words, it contains the triple (x,y,value).

It also contains 4 pointers to child nodes, which may be null. There is an algorithmic relationship between the keys and the child links.

Your inserts should look like this.

quadtree->insert(0.0, 0.0, value1)
quadtree->insert(0.0, 0.0, value2)

The first insert creates a (parent) node and inserts a value into it.

The second insert creates a child node, links to it, and inserts a value into it (which may happen to be the same as the first value).

Which child node is instantiated depends on the algorithm. If the algorithm is in the form [x) and the coordinate space lies in the range [0,1) then each child will span the range [0,0.5) and the point will be placed in the NW child.

I see no infinite recursion.


问:
How to avoid downcasting?
My question is about a special case of the super class Animal.

My Animal can moveForward() and eat().

Seal extends Animal.

Dog extends Animal.

And there's a special creature that also extends Animal called Human.

Human implements also a method speak() (not implemented by Animal).

In an implementation of an abstract method which accepts Animal I would like to use the speak() method. That seems not possible without doing a downcast. Jeremy Miller wrote in his article that a downcast smells.

What would be a solution to avoid downcasting in this situation?

答:
The problem is not that you are downcasting - it's that you are downcasting to Human. Instead, create an interface:

```<code>public interface CanSpeak{
    void speak();
}

public abstract class Animal{
    //....
}

public class Human extends Animal implements CanSpeak{
    public void speak(){
        //....
    }
}

public void mysteriousMethod(Animal animal){
    //....
    if(animal instanceof CanSpeak){
        ((CanSpeak)animal).speak();
    }else{
        //Throw exception or something
    }
    //....
}
</code>```

This way, the condition is not that the animal is Human - the condition is that it can speak. This means mysteriousMethod can work with other, non-human subclasses of Animal as long as they implement CanSpeak.

Title: How to avoid downcasting?

Body:
The problem is not that you are downcasting - it's that you are downcasting to Human. Instead, create an interface:

public interface CanSpeak{
    void speak();
}

public abstract class Animal{
    //....
}

public class Human extends Animal implements CanSpeak{
    public void speak(){
        //....
    }
}

public void mysteriousMethod(Animal animal){
    //....
    if(animal instanceof CanSpeak){
        ((CanSpeak)animal).speak();
    }else{
        //Throw exception or something
    }
    //....
}

This way, the condition is not that the animal is Human - the condition is that it can speak. This means mysteriousMethod can work with other, non-human subclasses of Animal as long as they implement CanSpeak.


答:
There are use cases were error codes are preferable to exceptions.

If your code can continue despite the error, but it needs reporting, then an exception is a poor choice because exceptions terminate the flow. For example, if you're reading in a data file and discover it contains some non-terminal piece of bad data it might be better to read in the rest of the file and report the error rather than fail outright.

The other answers have covered why exceptions should be preferred to error codes in general.


问:
Split up large interfaces
I'm using a large interface with about 50 methods to access a database. The interface has been written by a colleague of mine. We discussed this:

Me: 50 methods is too much. It's a code smell.

Colleague: What shall I do about it? You want the DB access - you have it.

Me: Yeah, but it's unclear and hardly maintainable in the future.

Colleague: OK, you are right, it's not nice. How should the interface look like then?

Me: How about 5 methods that return objects that have, like, 10 methods each?

Mmmh, but wouldn't this be the same? Does this really lead to more clarity? Is it worth the effort?

Every now and then I'm in a situation where I want an interface and the first thing that comes to mind is one, big interface. Is there a general design pattern for this?

Update (responding to SJuan's comment):

The "kind of methods": It's an interface for fetching data from a database. All methods have the form (pseudocode)

```<code>List<Typename> createTablenameList()
</code>```

Methods and tables are not exactly in a 1-1-relation, the emphasis is more on the fact that you always get some kind of list that comes from a database.

答: The Data Access Layers tend to have a lot of methods attached to one class. If you've ever worked with Entity Framework or other ORM tools, you'll see they generate 100s of methods. I assume you and your colleague are manually implementing it. It's not necessary a code smell, but it's not pretty to look at. Without knowing your domain, it's hard to say.</p>

Title: Split up large interfaces


问:
How to stop the WCF service (database queriying) running behind
I have a WCF service which will get an object with huge data from database in the form of collection.
I have a UI which has get and cancel buttons .

Get button : make service request and continue with data population with the returned data from service.I start it as below

```<code>Thread _workerThread = new Thread(DoExportTreeLoad);
_workerThread.Start();
</code>```

Cancel : stops the above thread.It does as below

```<code>_workerThread.Abort()
</code>```

My DoExportTreeLoad() has the synchronous service call which in turn hits database and gets data.

```<code>result = serivce.GetData(criteria);
</code>```

Problem: When I cancel the operation after requesting the service, the DAL code is still running in the background (getting data from database) where it should not happen.

As soon as i cancel the operation from UI ,the transaction (to get the data ) from database need to be aborted.
It leads to big performance problem.

Please help me with any way to end up the backend task when thread is cancelled.
Thanks in advance.

答:
There is no way to tell WCF to kill a request that is underway.  You would have to roll your own solution.  For example, have another method on the WCF object that you can call telling it to cancel any operation currently underway.

You may want to re-architect your solution to support this.  For example, when you start the big-data-retrieval function you could return immediately with a request-id.  Then have periodic events that are sent back to the client from the WCF component with data collected so far and a "cancel" argument you can set to cancel the operation.  Or have a method that the client can call to get data collected so far, passing in the request-id and provide a cancel method accepting the request-id.

Here is a similar question on SO: https://stackoverflow.com/questions/15324995/cancel-a-long-running-task-over-wcf-from-client


问:
calculate complexity of LinkedHashSet
I have an ArrayList<LinkedHashSet<String>> setOfStrings for example this arraylist internally is composed like:

```<code>positionX[hello,car,three,hotel,beach]
positionY[.....]
...
</code>```

I want to find car inside this data-structure, so I did it

```<code>for (Iterator<LinkedHashSet<String>> iterator = setOfStrings.iterator(); iterator.hasNext();) {
    LinkedHashSet<String> subSet = iterator.next();
    if (subSet.contains("hotel"))
        System.out.println("found");
}
</code>```

The for iterate over the entire arrayList and the complexity in the worst-case is O(n), but I'm confused on the complexity of the method contains() of set. In according of javadocs this method is executed in constant time, but I've heard that in certain cases the complexity might become O(n). Saying that, I'm not sure about the complexity of this snippet algorithm.

Can someone provide me an explanation of that?

答:
LinkedHashSet, for the intents and purposes of being accessed using contains is simply a hash set.  It uses the return from hashCode of the objects inserted in it to determine the position to place it in in the hash set.  If you have a collision, then it will then check the next element.  If that is occupied, it will then check the one after that, and so forth.  Therefore, for hash sets with relatively small capacity or types which do not return distinguishable hashCode values, you will see up to O(n) complexity for insertion or checking the esistence of an item in the hash set.  However most times you don't see collisions and so in most cases it will be O(1).

Combine this with a O(n) operation on all entires in your ArrayList, and you end up with O(n)*O(1) complexity on average or O(n).  However if the hashCode() does not properly distinguish values or if the capacity is small for the LinkedHashSet, you may see up to O(n*m) complexity (O(n)*O(m)) where n is the number of elements in your ArrayList and m being the number of elements on average in each LinkedHashSet.

Hope that answers your question!

Title: calculate complexity of LinkedHashSet


问:
ORM domain design pitfalls
Are there any patterns which seem sensible when designing an object oriented domain, but do not translate nicely onto a relational database schema?  If so, are there standard patterns that can be used instead?</p>

答:
Domains which have entities where the number of attributes (properties, parameters) that can be used to describe them is potentially vast, but the number that will actually apply to a given entity is relatively modest.

An example of such a domain would be a medical practice, where there are a vast number of possible symptoms, but the number of symptoms that any patient might have at any given time is comparatively small.

These kinds of domains are typically represented using an Entity-Attribute-Value (EAV) model.  This data representation is analogous to space-efficient methods of storing a sparse matrix, where only non-empty values are stored.

In the case of a medical domain, the problem space is complicated by the fact that any given symptom or medical test can have its own set of custom attributes, just as products sold in an online store can have custom specifications.

In fact, online stores have to deal with this problem also.  A book has a "number of pages" specification, while a memory module has a "number of bytes" specification, and the two attributes are not related at all.

So a set of attributes appropriate for each product is chosen from an attributes table.

The Attributes table might look like this:

```<code>AttributeID
AttributeDescription
UnitsID --> FK to Units table
</code>```

The ProductAttributes table might look like this:

```<code>ProductAttributeID
ProductID
AttributeID --> FK to Attributes table
Value
</code>```

Notice that Number of Bytes and Number of Pages aren't features of the database schema. Instead, they are soft-coded into the tables.  So there is no way to represent these features as part of the domain design.

ContentLicense: CC BY-SA 2.5

Title: ORM domain design pitfalls

Body:
Domains which have entities where the number of attributes (properties, parameters) that can be used to describe them is potentially vast, but the number that will actually apply to a given entity is relatively modest.

An example of such a domain would be a medical practice, where there are a vast number of possible symptoms, but the number of symptoms that any patient might have at any given time is comparatively small.

These kinds of domains are typically represented using an Entity-Attribute-Value (EAV) model.  This data representation is analogous to space-efficient methods of storing a sparse matrix, where only non-empty values are stored.

In the case of a medical domain, the problem space is complicated by the fact that any given symptom or medical test can have its own set of custom attributes, just as products sold in an online store can have custom specifications.

In fact, online stores have to deal with this problem also.  A book has a "number of pages" specification, while a memory module has a "number of bytes" specification, and the two attributes are not related at all.

So a set of attributes appropriate for each product is chosen from an attributes table.

The Attributes table might look like this:

AttributeID
AttributeDescription
UnitsID --> FK to Units table

The ProductAttributes table might look like this:

ProductAttributeID
ProductID
AttributeID --> FK to Attributes table
Value

Notice that Number of Bytes and Number of Pages aren't features of the database schema. Instead, they are soft-coded into the tables.  So there is no way to represent these features as part of the domain design.


问:
Reduce number of if statements through design pattern
I had a loop through object Process, each process instance can be of a different type, derived from Process base class (e.g.: Process1, Process2,...). Each derived type of Process has different properties. For instance: some Processes are indexable, this is notified by IsIndexable flag. When a Process is indexable has some additional properties (for instance: AccessDate) that non-indexable process doesn't have.
Now I have to cycle on each Process in request.Process (remember indexable Processes are different from others)

foreach (Process process in request.Processes)
{
     if(process.getType().Name.Equals("Process1")) // indexable process
     {
         ((Process1)process).Name = "aName";
         ((Process1)process).AccessDate = DateTime.Now;
     }
     else if(process.getType().Name.Equals("Process2")) // non indexable process
     {
         ((Process2)process).Name = "anotherNane";
         //compile error - AccessDate don't exist for type Process2
         //((Process2)process).AccessDate = DateTime.Now;
     }
}
```

<p>Since I hate that cascading if I have rewritten using interface:</p>

<pre class="lang-cs prettyprint-override"><code>IProcessable processableImpl = // some Unity stuff based on request type
foreach (Process process in request.Processes)
{
     processableImpl.fillTheRightProperties(process);
}
</code>```

processableImpl is injected in a different manner based on the request.Type. At this point fillTherRightProperties method will do the work for me on the current process.

public interface IProcessable
{
    void fillTheRightProperties(Process process);
}

public class IndexableProcess : IProcessable
{
    void fillTheRightProperties(Process process){
        Process1 process1 = process as Process1;

        if(process1==null) throw MyException("Process1 expected");

        process1.Name = "aName";
        process1.AccessDate = DateTime.Now;
    }
}

public class NonIndexableProcess : IProcessable
{
    void fillTheRightProperties(Process process){
        Process2 process2 = process as Process2;

        if(process2==null) throw MyException("Process2 expected");

        process2.Name = "aName";
    }
}
```

This is more beautiful than a cascading if but I feel still not as beautiful as it could be. I feel a violation of responsability, since the concrete class edit process property elsewhere, and I'm afraid to read this code a week after.

答:
Use a hash which contains as key the name of the Process and as value the Object containing the process. That way you get just one line of code:

Note: the following is in perl since I don't know C#, but the logic is the same

```<code>$hashContainingProcesses{processName}.doSomething();
</code>```

Depending on how C# will handle this you probably want to check first if the key exsists.

Body:
Use a hash which contains as key the name of the Process and as value the Object containing the process. That way you get just one line of code:

Note: the following is in perl since I don't know C#, but the logic is the same

$hashContainingProcesses{processName}.doSomething();

Depending on how C# will handle this you probably want to check first if the key exsists.


答:
Below is an example using an interface and two implementations in a console application:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var processes = new List<IProcessable>();
            processes.Add(new Process1());
            processes.Add(new Process2());

            foreach (IProcessable item in processes)
            {
                item.FillTheRightProperties();
            }

            Console.WriteLine();
            Console.WriteLine("Press Enter/Return to exit...");
            Console.ReadLine();
        }
    }

    interface IProcessable
    {
        void FillTheRightProperties();
    }

    class Process1 : IProcessable
    {
        public string Name { get; set; }
        public DateTime AccessDate { get; set; }

        public void FillTheRightProperties()
        {
            this.Name = "aName";
            this.AccessDate = DateTime.Now;

            Console.WriteLine("Properties filled: {0}, {1}", this.Name, this.AccessDate);
        }
    }

    class Process2 : IProcessable
    {
        public string Name { get; set; }

        public void FillTheRightProperties()
        {
            this.Name = "aName";

            Console.WriteLine("Properties filled: {0}", this.Name);
        }
    }
}
```

The key line is in the foreach where we use the interface rather than casting to a concrete class.

To map this to your example request.Processes would be a List<IProcessItem> meaning we can guarantee that the DoSomething() method exists, and there is no need to cast to a concrete class.

The base class can also be used, but it's purpose would be to hold common code only.

Title: Reduce number of if statements through design pattern

Body:
I had a loop through object Process, each process instance can be of a different type, derived from Process base class (e.g.: Process1, Process2,...). Each derived type of Process has different properties. For instance: some Processes are indexable, this is notified by IsIndexable flag. When a Process is indexable has some additional properties (for instance: AccessDate) that non-indexable process doesn't have.
Now I have to cycle on each Process in request.Process (remember indexable Processes are different from others)

foreach (Process process in request.Processes)
{
     if(process.getType().Name.Equals("Process1")) // indexable process
     {
         ((Process1)process).Name = "aName";
         ((Process1)process).AccessDate = DateTime.Now;
     }
     else if(process.getType().Name.Equals("Process2")) // non indexable process
     {
         ((Process2)process).Name = "anotherNane";
         //compile error - AccessDate don't exist for type Process2
         //((Process2)process).AccessDate = DateTime.Now;
     }
}
```

<p>Since I hate that cascading if I have rewritten using interface:</p>

<pre class="lang-cs prettyprint-override"><code>IProcessable processableImpl = // some Unity stuff based on request type
foreach (Process process in request.Processes)
{
     processableImpl.fillTheRightProperties(process);
}
</code>```

processableImpl is injected in a different manner based on the request.Type. At this point fillTherRightProperties method will do the work for me on the current process.

public interface IProcessable
{
    void fillTheRightProperties(Process process);
}

public class IndexableProcess : IProcessable
{
    void fillTheRightProperties(Process process){
        Process1 process1 = process as Process1;

        if(process1==null) throw MyException("Process1 expected");

        process1.Name = "aName";
        process1.AccessDate = DateTime.Now;
    }
}

public class NonIndexableProcess : IProcessable
{
    void fillTheRightProperties(Process process){
        Process2 process2 = process as Process2;

        if(process2==null) throw MyException("Process2 expected");

        process2.Name = "aName";
    }
}
```

This is more beautiful than a cascading if but I feel still not as beautiful as it could be. I feel a violation of responsability, since the concrete class edit process property elsewhere, and I'm afraid to read this code a week after.

Body:
Below is an example using an interface and two implementations in a console application:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var processes = new List<IProcessable>();
            processes.Add(new Process1());
            processes.Add(new Process2());

            foreach (IProcessable item in processes)
            {
                item.FillTheRightProperties();
            }

            Console.WriteLine();
            Console.WriteLine("Press Enter/Return to exit...");
            Console.ReadLine();
        }
    }

    interface IProcessable
    {
        void FillTheRightProperties();
    }

    class Process1 : IProcessable
    {
        public string Name { get; set; }
        public DateTime AccessDate { get; set; }

        public void FillTheRightProperties()
        {
            this.Name = "aName";
            this.AccessDate = DateTime.Now;

            Console.WriteLine("Properties filled: {0}, {1}", this.Name, this.AccessDate);
        }
    }

    class Process2 : IProcessable
    {
        public string Name { get; set; }

        public void FillTheRightProperties()
        {
            this.Name = "aName";

            Console.WriteLine("Properties filled: {0}", this.Name);
        }
    }
}

The key line is in the foreach where we use the interface rather than casting to a concrete class.

To map this to your example request.Processes would be a List<IProcessItem> meaning we can guarantee that the DoSomething() method exists, and there is no need to cast to a concrete class.

The base class can also be used, but it's purpose would be to hold common code only.


问:
Good approach for hundreds of comsumers and big files
I have several files (nearly 1GB each) with data. Data is a string line.

I need to process each of these files with several hundreds of consumers. Each of these consumers does some processing that differs from others. Consumers do not write anywhere concurrently. They only need input string. After processing they update their local buffers. Consumers can easily be executed in parallel.

Important: With one specific file each consumer has to process all lines (without skipping) in correct order (as they appear in file). The order of processing different files doesn't matter.

Processing of a single line by one consumer is comparably fast. I expect less than 50 microseconds on Corei5.

So now I'm looking for the good approach to this problem.
This is going to be be a part of a .NET project, so please let's stick with .NET only (C# is preferable).

I know about TPL and DataFlow. I guess that the most relevant would be BroadcastBlock. But i think that the problem here is that with each line I'll have to wait for all consumers to finish in order to post the new one. I guess that it would be not very efficient.

I think that ideally situation would be something like this:

One thread reads from file and writes to the buffer.

Each consumer, when it is ready, reads the line from the buffer concurrently and processes it.

The entry from the buffer shouldn't be deleted as one consumer reads it. It can be deleted only when all consumers have processed it.

TPL schedules consumer threads itself.

If one consumer outperforms the others, it shouldn't wait and can read more recent entries from the buffer.

Am i right with this kind of approach? Whether yes or not, how can i implement the good solution?

I was suggested to move the question here as more appropriate place from StackOverflow.

Update:
According to david.pfx comment here is some detailing. Performance is at the first place, ease of maintenance is at the second.

答: Use a different channel on a message queue for each consumer.  For each line in one of your big files write a message to each channel (e.g. each consumer).  Each consumer can process messages on its channel deleting the messages once received.</p>


答:
Colleague: OK, you are right, it's not nice. How should the interface look like then?

Me: How about 5 methods that return objects that have, like, 10 methods each?

That's not good criteria (there is no criteria at all in that statement actually). You can group them by (assuming your application is a financial transactions app, for my examples):

functionality (inserts, updates, selects, transactions, metadata, schema, etc)

entity (user DAO, deposit DAO, etc.)

application area (financial transactions, user management, totals etc)

abstraction level (all table access code is a separate module; all select APIs are in their own hierarchy, transaction support is separate, all conversion code in a module, all validation code in a module, etc)

Mmmh, but wouldn't this be the same? Does this really lead to more clarity? Is it worth the effort?

If you choose the right criteria, definitely. If you do not, definitely not :).

A few examples:

look at ADODB objects for a simplistic example of OO primitives (your DB API probably already offers this)

look at Django data model (https://docs.djangoproject.com/en/dev/topics/db/models/) for a data model idea with a high level of abstraction (in C++ you will probably need a bit more boiler plate code, but it's a nice idea). This implementation is designed with a "model" role in mind, within the MVC design pattern.

look at the sqlite API for a flat API idea (http://www.sqlite.org/c3ref/funclist.html), consisting of just functional primitives (C API).

Title: Split up large interfaces

Body:
I'm using a large interface with about 50 methods to access a database. The interface has been written by a colleague of mine. We discussed this:

Me: 50 methods is too much. It's a code smell.

Colleague: What shall I do about it? You want the DB access - you have it.

Me: Yeah, but it's unclear and hardly maintainable in the future.

Colleague: OK, you are right, it's not nice. How should the interface look like then?

Me: How about 5 methods that return objects that have, like, 10 methods each?

Mmmh, but wouldn't this be the same? Does this really lead to more clarity? Is it worth the effort?

Every now and then I'm in a situation where I want an interface and the first thing that comes to mind is one, big interface. Is there a general design pattern for this?

Update (responding to SJuan's comment):

The "kind of methods": It's an interface for fetching data from a database. All methods have the form (pseudocode)

```<code>List<Typename> createTablenameList()
</code>```

Methods and tables are not exactly in a 1-1-relation, the emphasis is more on the fact that you always get some kind of list that comes from a database.


问:
Rectangle class java.lang.Object
Can someone please explain to me the difference or benefits rather to using the rectangle class

```<code>ex. Rectangle r1 = new Rectangle(x,y,w,h);
</code>```

versus the graphics class drawRec method?

```<code>g.drawRec(x,y,w,h);
</code>```

I'm thinking that you can create a new object outside of paint() or paintcomponent() which gives creating an object more options and maybe the associated methods is a bonus?  I'm just speculating though because the tutorial I was going through switched from using one to the other without explaining why.  I believe I understand how to use them just not when it's better to use which. Please try to keep your responses at the beginner level seeing as how I'm just starting out but of course any assistance is GREATLY appreciated.  Thanks!!

Here is a code segment of what I'm working with:

```<code>public void paintComponent(Graphics g){
    g.drawImage(yellowBall, xCoor, yCoor, this);
    Rectangle r1 = new Rectangle((boardXSize/2), (boardYSize/2),50, 50);
    g.setColor(Color.red);
    g.fillRect(r1.x, r1.y,r1.width, r1.height);

    repaint();

}
</code>```

答: You use instances of Rectangle when you have to manage them for some reason (e.g. in a drawing program or some kind of window or layout management). There is hardly a good reason to create them solely for calling Graphics.fillRect, as in your example.</p>

Title: Rectangle class java.lang.Object


问:
Mental Models or Real-World-Metaphors for Functional Programming
Does anyone have a good mental model or metaphor for functional programming which references something in the real world?

Object Oriented programing intuitively makes sense to me. There are things that have properties and sometimes they also can do stuff or perform calculations on their properties (methods). (Ex: Car, Shape, Cat).

I bear functional programming no ill will whatsoever and I am not interested in a debate about the virtues of the two. I just need a metaphor or mental model to work with as I have with Object Oriented programming.

What are some good mental models or real world metaphors for programming in a functional paradigm? There is something about functions composed of functions processing functions which leaves one without a firm place to stand and cogitate.

答: Everything's a value, and you apply functions to values (which may be functions) to produce new values, preferably without producing any side effects.</p>


答:
Does anyone have a good mental model for functional programming?

Mathematics. Functional programming is inspired by and modeled on mathematics. Mathematical functions don't have state, don't have side effects, etc., and so it is with FP. If you think about FP in terms of mathematical functions rather than using an OO-style "how do I do this to that" approach, you'll be in good shape. If you try to bring OO sensibilities to FP, though, you'll be swimming against the current.

Title: Mental Models or Real-World-Metaphors for Functional Programming

Body:
Does anyone have a good mental model or metaphor for functional programming which references something in the real world?

Object Oriented programing intuitively makes sense to me. There are things that have properties and sometimes they also can do stuff or perform calculations on their properties (methods). (Ex: Car, Shape, Cat).

I bear functional programming no ill will whatsoever and I am not interested in a debate about the virtues of the two. I just need a metaphor or mental model to work with as I have with Object Oriented programming.

What are some good mental models or real world metaphors for programming in a functional paradigm? There is something about functions composed of functions processing functions which leaves one without a firm place to stand and cogitate.


问:
How to comment the file system?
When certain parts of code are unusual or unclear, common practice is to leave a comment explaining why it is so. However, sometimes a filesystem may have unusual configuration, such as a directory with 0477 privileges. Is there any convention for leaving comments about this?

I am writing a 'Developers Wiki' for the company as that would be the place for such things. However I would prefer something more standard if it exists and more accessible when, for instance, the next guys has to SSH in from home in the middle of the night and he might not think to check the wiki (or even have access to it).

答:
In a project, it's typical to have a readme or a summary of the project, and in it, a quick description of the project structure is warranted.  There, I think you could place an explanation for the permissions of the directories.  If the developer should fail to check the wiki, hopefully they will think to check the readme.

Does that answer your question?

Title: How to comment the file system?


问:
Choosing the right language for the job
I'm currently working for a company on the engineering team of about 5-6 people and have been given the job of heading up the redesign of an embedded system tester. We've decided the general requirements and attributes that would be desirable in the system, and now I have to decide on a language to use for the system, or at the very least come up with a list of languages with pros and cons to present to the team.

The general idea of the project is that we currently have a tester written in c++, which was never designed to be a tester, but instead has evolved to be such over the course of 3-4 years due to need. Writing tests for a new product requires modifying the 'framework' and writing code that is completely non-human readable or intuitive due to the way the system was originally designed. Now, we've decided that the time to modify this tester for each new product that we want to test has become too high and want to partially re-write the system so that we can program the actual tests in a scripting language that would then use the modified c++ framework on the back end to test the actual systems. The c++ framework would be responsible for doing all the actual work and the scripting language would just integrate with that to tell the framework what to do.

Never having programmed in a scripting language (we program embedded systems), I've run into a wall where I have no experience with any of the languages that we could possibly use, but must somehow give pros and cons of each language so that we can choose the best one for the job.

Currently my short list of possibilities includes:

Python

TCL

Lua

Perl

My question is this: How can a person evaluate a language that he/she has never used before? What criteria are good indicators for a languages potential usability on a project?

While helpful suggestions for my particular case are appreciated, I feel that this is a good skill to possess and would like to be able to apply this to many different projects if at all possible

答:
Certainly the popularity of a programming language is one factor to consider.
TIOBE offers a useful index of language popularity including graphs that show change over time.

TIOBE points out that the index "ratings are based on the number of skilled engineers world-wide, courses and third party vendors. Popular search engines such as Google, Bing, Yahoo!, Wikipedia, Amazon, YouTube and Baidu are used to calculate the ratings. It is important to note that the TIOBE index is not about the best programming language or the language in which most lines of code have been written."

Title: Choosing the right language for the job


答:
Functional programming is all about gluing smaller functions together to achieve your results. A decent mental model (for me, at least) is an assembly line. Each function that gets composed is one more step in the assembly process. Consider this function here:

```<code>smallest  = head . sort
</code>```

In Haskell, this function will return the smallest element in a list. The assembly line first sorts the input, then returns the first element (assuming it's sorted least to greatest.) If we wanted to only get the smallest even value, then we can change the assembly line to look like the following:

```<code>smallestEven = head . sort . filter even
</code>```

It's just one more step on the conveyor belt.

In a nutshell, functions just describe the steps taken to convert the raw input (the parts) into the processed good (the output.)

Body:
Functional programming is all about gluing smaller functions together to achieve your results. A decent mental model (for me, at least) is an assembly line. Each function that gets composed is one more step in the assembly process. Consider this function here:

smallest  = head . sort

In Haskell, this function will return the smallest element in a list. The assembly line first sorts the input, then returns the first element (assuming it's sorted least to greatest.) If we wanted to only get the smallest even value, then we can change the assembly line to look like the following:

smallestEven = head . sort . filter even

It's just one more step on the conveyor belt.

In a nutshell, functions just describe the steps taken to convert the raw input (the parts) into the processed good (the output.)


问:
How could your company's learning/development department best serve you?
I'll preface my question with a disclaimer - I am not an engineer, I'm just someone who works with them full-time, in a learning and development capacity.

Given that, one of the comments I get regularly from the engineers I'm tasked with developing is that they feel that they're having solutions (both technical and non-technical) for development "pushed" at them vs. anyone from my field consulting with them to determine what they really need.

So my question is - if you could give your company a list of the top 3-5 things they could do - in a classroom, or elsewhere - to develop meaningful skills that would help you be a better engineer, a better employee, and one more likely to STAY with the company for the long haul, what would make the cut and why?

Thanks in advance for your responses.

答: Provide a feedback and suggestion mechanism. Collect regular samples of what people want. Collect periodic samplings of our development goals (if any) and try to correlate these to possible courses. Use technical resources to develop your course list or lesson plans, etc when it is not in your domain and there is a high demand for a number of courses or classes on the topic.</p>


答:
Any place where your code expects an unusual configuration, have it explicitly check for that configuration and clearly explain the expectation in the appropriate error message / log file entry.

If Ops calls your guy at 2 am with

"TheApp crashed with a message 'error 2468: /rootdir/specialdir must have 0477 privileges'", then at least his SSH fix will be quick.

On a side note, if at all possible, try to avoid this situation.  Standard/vanilla configurations are easier to maintain / harder to mess up.

Clarification: in addition to any documentation, also ensure the code "documents" the issue with explicit checks and error handling.  The very first thing a person reads when there's a problem isn't the doc or the wiki, it's the error message.

Title: How to comment the file system?

Body:
When certain parts of code are unusual or unclear, common practice is to leave a comment explaining why it is so. However, sometimes a filesystem may have unusual configuration, such as a directory with 0477 privileges. Is there any convention for leaving comments about this?

I am writing a 'Developers Wiki' for the company as that would be the place for such things. However I would prefer something more standard if it exists and more accessible when, for instance, the next guys has to SSH in from home in the middle of the night and he might not think to check the wiki (or even have access to it).


答:
To add to @Neil's answer above, putting a readme file in the directory in question would also be very useful.  6 months (or 6 years) after the project is done, developers might not even know which project caused the change, to find the wiki/readme.  Similar to comments in code, this puts the explanation right with the problem/outlier.

This solution also can help your SysAdmins help debug and correct the problem without even having to call you.  These people won't have any idea which project is involved, but they will have the information right in front of them.

Title: How to comment the file system?


问:
What is the best way to get a method name in runtime?
Here is a little background of my problem: I implemented a singleton logger class which is being called from several projects.

I want to log the name of the class as well as the name of the method asked for logging.

So far, I thought about two ways to get the name of the method and the class - either by reflection or by manually writing them.

The advantage of using reflection is that whenever the name of the class or the method will be renamed, which is not that often, it will be updated automatically.

The disadvantage of reflection is that it is performance consuming and it is suggested not to use it whenever you can avoid it, as can be seen in the documentation of reflection (http://docs.oracle.com/javase/tutorial/reflect/index.html) or in various threads online.

What would be the best way and why?

答:
I presume we're talking about Java by the link.  You're right of course.  The tradeoff is speed vs development time / hassle.

A popular logging library called log4j takes a classname or string as a initialization parameter.  Successive logging performed by the class will automatically offer the class name as possible information to output into the log without having to specify it at every line.  I don't find it to be that much of a hassle done like this.  In fact, in eclipse if you check under Java -> Code Style -> Code Templates, you can predefine new classes to automatically instantiate a logger passing the class name as a parameter to save you time, at least for what concerns the class name.

Alternatively, you can use AspectJ as a means to get a handle of a method prior to a call to a logger so that you can add the class name as well.  AspectJ can work in runtime as well as at compile time, and in the latter case, you will not see the performance drop that you would see using reflection since it modifies the code prior to compilation.

Hope that helps!


答:
The simplest thing to do is look at the JavaDocs for Rectangle. If you want any of these abilities, use a Rectangle.

Also, as @user281377 notes, a single Rectangle object is easier to manage, store in a List, persist, etc. than four ints.

Title: Rectangle class java.lang.Object

Body:
Can someone please explain to me the difference or benefits rather to using the rectangle class

```<code>ex. Rectangle r1 = new Rectangle(x,y,w,h);
</code>```

versus the graphics class drawRec method?

```<code>g.drawRec(x,y,w,h);
</code>```

I'm thinking that you can create a new object outside of paint() or paintcomponent() which gives creating an object more options and maybe the associated methods is a bonus?  I'm just speculating though because the tutorial I was going through switched from using one to the other without explaining why.  I believe I understand how to use them just not when it's better to use which. Please try to keep your responses at the beginner level seeing as how I'm just starting out but of course any assistance is GREATLY appreciated.  Thanks!!

Here is a code segment of what I'm working with:

```<code>public void paintComponent(Graphics g){
    g.drawImage(yellowBall, xCoor, yCoor, this);
    Rectangle r1 = new Rectangle((boardXSize/2), (boardYSize/2),50, 50);
    g.setColor(Color.red);
    g.fillRect(r1.x, r1.y,r1.width, r1.height);

    repaint();

}
</code>```


问:
Preferred way for dealing with customer-defined data in enterprise application
Let's say that we have a small enterprise web (intranet) application for managing data for car dealers. It has screens for managing customers, inventory, orders, warranties and workshops.

This application is installed at 10 customer sites for different car dealers.

First version of this application was created without any way to provide for customer-specific data. For example, if dealer A wanted to be able to attach a photo to a customer, dealer B wanted to add e-mail contact to each workshop, and dealer C wanted to attach multiple PDF reports to a warranty, each and every feature like this was added to the application, so all of the customers received everything on new update.

However, this will inevitably lead to conflicts as the number of customers grow as their usage patterns are unique, and if, for instance, a specific dealer requested to have an ability to attach (for some reason) a color of inventory item (and be able to search by this color) as a required item, others really wouldn't need this feature, and definitely will not want it to be a required item. Or, one dealer would like to manage e-mail contacts for their employees on a separate screen of the application.

I imagine that a solution for this is to use a kind of plugin system, where we would have a core of the application that provides for standard features like customers, inventory, etc, and all of the customer's installed plugins.

There would be different kinds of plugins - standalone screens like e-mail contacts for employees, with their own logic, and customer plugin which would extend or decorate inventory items (like photo or color).

Inventory (customer,order,...) plugins would require to have installation procedure, hooks for plugging into the item editor, item displayer, item filtering for searching, backup hook and such.

Is this the right way to solve this problem?

答:
When you build modular systems you have to think about how extensions will be permitted to manipulate/augment your exposed extension points.  This always adds some complexity to a design, but when well done, provides for a superior product.  Consider how various browsers are designed for plugins.

Practially speaking I would build extension points on an as-needed basis in order to accommodate desired customizations.  That is, instead of simply extending your software to do X, consider how to best provide an extension point that would allow X to be plugged in.


问:
Why was C# made with "new" and "virtual+override" keywords unlike Java?
In Java there are no virtual, new, override keywords for method definition. So the working of a method is easy to understand. Cause if DerivedClass extends BaseClass and has a method with same name and same signature of BaseClass then the overriding will take place at run-time polymorphism (provided the method is not static).

BaseClass bcdc = new DerivedClass();
bcdc.doSomething() // will invoke DerivedClass's doSomething method.
```

<hr>

<p>Now come to C# there can be so much confusion and hard to understand how the <code>new</code> or <code>virtual+derive</code> or new + virtual override is working. </p>

<p>I'm not able to understand why in the world I'm going to add a method in my <code>DerivedClass</code> with same name and same signature as <code>BaseClass</code> and define a new behaviour but at the run-time polymorphism, the <code>BaseClass</code> method will be invoked! (which is not overriding but logically it should be). </p>

<p>In case of <code>virtual + override</code> though the logical implementation is correct, but the programmer has to think which method he should give permission to user to override at the time of coding. Which has some <em>pro-con</em> (let's not go there now).</p>

<p>So why in C# there are so much space for <em>un</em>-logical reasoning and confusion. So may I reframe my question as in which real world context should I think of use <code>virtual + override</code> instead of <code>new</code> and also use of <code>new</code> instead of <code>virtual + override</code>?</p>

<hr>

<p>After some very good answers especially from Omar, I get that C# designers gave stress more about programmers should think before they make a method, which is good and handles some rookie mistakes from Java. </p>

<p>Now I've a question in mind. As in Java if I had a code like</p>

<pre class="lang-java prettyprint-override"><code>Vehicle vehicle = new Car();
vehicle.accelerate();
</code>```

and later I make new class SpaceShip derived from Vehicle. Then I want to change all car to a SpaceShip object I just have to change single line of code

```<code>Vehicle vehicle = new SpaceShip();
vehicle.accelerate();
</code>```

This will not break any of my logic at any point of code.

But in case of C# if SpaceShip does not override the Vehicle class' accelerate and use new then the logic of my code will be broken. Isn't that a disadvantage?

答: It was done because it's the correct thing to do. The fact is that allowing all methods to be overridden is wrong; it leads to the fragile base class problem, where you have no way of telling if a change to the base class will break subclasses. Therefore you must either blacklist the methods that shouldn't be overridden or whitelist the ones that are allowed to be overridden. Of the two, whitelisting is not only safer (since you can't create a fragile base class accidentally), it also requires less work since you should avoid inheritance in favor of composition.


答:
As Robert Harvey said, it's all in what you're used to.  I find Java's lack of this flexibility odd.

That said, why have this in the first place?  For the same reason that C# has public, internal (also "nothing"), protected, protected internal, and private, but Java just has public, protected, nothing, and private.  It provides finer grain control over the behavior of what you're coding, at the expense of having more terms and keywords to keep track of.

In the case of new vs. virtual+override, it goes something like this:

If you want to force subclasses to implement the method, use abstract, and override in the subclass.

If you want to provide functionality but allow the subclass to replace it, use virtual, and override in the subclass.

If you want to provide functionality which subclasses should never need to override, don't use anything.

If you then have a special case subclass which does need to behave differently, use new in the subclass.

If you want to ensure that no subclass can ever override the behavior, use sealed in the base class.

For a real-world example: A project I worked on processed ecommerce orders from many different sources.  There was a base OrderProcessor which had most of the logic, with certain abstract/virtual methods for each source's child class to override.  This worked fine, up until we got a new source which had a completely different way of processing orders, such that we had to replace a core function.  We had two choices at this point: 1) Add virtual to the base method, and override in the child; or 2) Add new to the child.

While either one could work, the first would make it very easy to override that particular method again in the future.  It'd show up in auto-complete, for example.  This was an exceptional case, however, so we chose to use new instead.  That preserved the standard of "this method doesn't need to be overridden", while allowing for the special case where it did.  It's a semantic difference which makes life easier.

Do note, however, that there is a behavior difference associated with this, not just a semantic difference.  See this article for details.  However, I've never run into a situation where I needed to take advantage of this behavior.

Title: Why was C# made with "new" and "virtual+override" keywords unlike Java?

Body:
In Java there are no virtual, new, override keywords for method definition. So the working of a method is easy to understand. Cause if DerivedClass extends BaseClass and has a method with same name and same signature of BaseClass then the overriding will take place at run-time polymorphism (provided the method is not static).

BaseClass bcdc = new DerivedClass();
bcdc.doSomething() // will invoke DerivedClass's doSomething method.
```

<hr>

<p>Now come to C# there can be so much confusion and hard to understand how the <code>new</code> or <code>virtual+derive</code> or new + virtual override is working. </p>

<p>I'm not able to understand why in the world I'm going to add a method in my <code>DerivedClass</code> with same name and same signature as <code>BaseClass</code> and define a new behaviour but at the run-time polymorphism, the <code>BaseClass</code> method will be invoked! (which is not overriding but logically it should be). </p>

<p>In case of <code>virtual + override</code> though the logical implementation is correct, but the programmer has to think which method he should give permission to user to override at the time of coding. Which has some <em>pro-con</em> (let's not go there now).</p>

<p>So why in C# there are so much space for <em>un</em>-logical reasoning and confusion. So may I reframe my question as in which real world context should I think of use <code>virtual + override</code> instead of <code>new</code> and also use of <code>new</code> instead of <code>virtual + override</code>?</p>

<hr>

<p>After some very good answers especially from Omar, I get that C# designers gave stress more about programmers should think before they make a method, which is good and handles some rookie mistakes from Java. </p>

<p>Now I've a question in mind. As in Java if I had a code like</p>

<pre class="lang-java prettyprint-override"><code>Vehicle vehicle = new Car();
vehicle.accelerate();
</code>```

and later I make new class SpaceShip derived from Vehicle. Then I want to change all car to a SpaceShip object I just have to change single line of code

```<code>Vehicle vehicle = new SpaceShip();
vehicle.accelerate();
</code>```

This will not break any of my logic at any point of code.

But in case of C# if SpaceShip does not override the Vehicle class' accelerate and use new then the logic of my code will be broken. Isn't that a disadvantage?


答:
Relationships.

Friend: Given two people, a friend relationship follows these general laws

Have good will towards each other

Thinks each other are a friend to them (so the laws must be fulfilled by both members in this relationship)

Enjoys spending time with each other

Monoid: Given multiple items and a function that takes 2 of the items and returns 1, a monoidal relationship follows these general laws

There is one of those items (only one, called identity) which passed to the function with any other item will ensure the function always returns the other item (0 + 1 = 1, thus 0 is the identity when the items are numbers and the function is addition)

The function cannot operate on or return items not in the set it has a monoidal relationship with

The function is associative and can be used with the items in a somewhat order independent manner, this means a * (b * c) = (a * b) * c which says you can multiply a by the result of b*c or c by the result of a*b and the result will be the same whichever you do first.

Functional programming is all about generalizations, friend is a very general relationship that can be seen in numerous scenarios, but in all various formats it generally follows the laws above.

Recognizing the laws that governs the relationships between things, you can create general implementations that work on any format of things that has that type of relationship. In functional programming you try to identify the relationships between things so that they can be classified and treated generally.

You want a metaphor from the real world? Look at how things are related and try to identify general laws (as in applicable to multiple scenarios where things other than the laws may vary). There is a relationship between a register clerk and a shopper at a store, it has some general laws, software has been developed to facilitate the goals of people in that general relationship in the way of POS systems. Similarly when you start seeing these general laws dictating how things are related, you can start relying on the laws of those relationships in writing your software rather than the specific particulars of an instance of a relationship.


答:
The design of Java is such that given any reference to an object, a call to a particular method name with particular parameter types, if it is allowed at all, will always invoke the same method.  It's possible that implicit parameter-type conversions may be affected by the type of a reference, but once all such conversions have been resolved, the type of the reference is irrelevant.

This simplifies the runtime, but can cause some unfortunate problems.  Suppose GrafBase does not implement void DrawParallelogram(int x1,int y1, int x2,int y2, int x3,int y3), but GrafDerived implements it as a public method which draws a parallelogram whose computed fourth point is opposite the first.  Suppose further that a later version of GrafBase implements a public method with the same signature, but its computed fourth point opposite the second.  Clients which receive expect a GrafBase but receive a reference to a GrafDerived will expect DrawParallelogram to compute the forth point in the fashion of the new GrafBase method, but clients who have been using GrafDerived.DrawParallelogram before the base method was changed will expect the behavior which GrafDerived originally implemented.

In Java, there would be no way for the author of GrafDerived to make that class coexist with clients that use the new GrafBase.DrawParallelogram method (and may be unaware that GrafDerived even exists) without breaking compatibility with existing client code that used GrafDerived.DrawParallelogram before GrafBase defined it.  Since the DrawParallelogram can't tell what kind of client is invoking it, it must behave identically when invoked by kinds of client code.  Since the two kinds of client code have different expectations as to how it should behave, there's no way GrafDerived can avoid violating the legitimate expectations of at one of them (i.e. breaking legitimate client code).

In C#, if GrafDerived is not recompiled, the runtime will assume that code which invokes DrawParallelogram method upon references of type GrafDerived will be expecting the behavior GrafDerived.DrawParallelogram() had when it was last compiled, but code which invokes the method upon references of type GrafBase will be expecting GrafBase.DrawParallelogram (the behavior that was added).  If GrafDerived is later recompiled in the presence of the enhanced GrafBase, the compiler will squawk until the programmer either specifies whether his method was intended to be a valid replacement for inherited member GrafBase, or whether its behavior needs to be tied to references of type GrafDerived, but should not replace the behavior of references of type GrafBase.

One might reasonably argue that having a method of GrafDerived do something different from a member of GrafBase which has the same signature would indicate bad design, and as such shouldn't be supported.  Unfortunately, since the author of a base type has no way of knowing what methods might be added to derived types, nor vice versa, the situation where base-class and derived-class clients have different expectations for like-named methods is essentially unavoidable unless nobody's allowed to add any name which someone else might also add.  The question is not whether such a name duplication should happen, but rather how to minimize the harm when it does.


问:
Is storing pointer (of new'd object) in static collection from object constructor a common idiom in C++
I am reviewing an approach I see commonly used in storing objects (e.g. a socket client object). Namely, usage of a static container to hold the objects. Said objects are created by some helper function as follows:

```<code>create_client(params) {
  ...
  client* cl = new client(...);
  return cl;
}
</code>```

The thing that confused me at first was function called like this:

```<code>if (!create_client (...))
   //generate error message
</code>```

i.e. a copy of the pointer just seems to be thrown away.

But on investigation I see this in the client constructor:

```<code>client::client(...) {
    ...
    coll[id] = this;
}
</code>```

Where coll is a map of id to a pointer to the object. But anyway, just a collection.  coll is static (not sure if that is relevant).

Is there a name for this idiom?  Is it good practice?

答:
Not so familiar with C++, but I do not like the assignment into the static structure from the constructor, because:

1) Introduces a dependency: now the contained class needs to know about the containing instance. You cannot reuse the class without either rewritting or using the same structure.

2) It causes a reference leak from the constructor, since the reference to the class is available to other threads before the constructor has finished executing.

At the very least, I would have moved the instance assignment from the constructor to the create_client function.


答:
Is there a name for this idiom? Is it good practice?

No, and no, unless you count "Terrible" as an idiom name. There is no such thing as idiomatic mutable global state. Idioms exist to avoid such crap.

Title: Is storing pointer (of new'd object) in static collection from object constructor a common idiom in C++

Body:
I am reviewing an approach I see commonly used in storing objects (e.g. a socket client object). Namely, usage of a static container to hold the objects. Said objects are created by some helper function as follows:

```<code>create_client(params) {
  ...
  client* cl = new client(...);
  return cl;
}
</code>```

The thing that confused me at first was function called like this:

```<code>if (!create_client (...))
   //generate error message
</code>```

i.e. a copy of the pointer just seems to be thrown away.

But on investigation I see this in the client constructor:

```<code>client::client(...) {
    ...
    coll[id] = this;
}
</code>```

Where coll is a map of id to a pointer to the object. But anyway, just a collection.  coll is static (not sure if that is relevant).

Is there a name for this idiom?  Is it good practice?


问:
Dealing with state problems in functional programming
I've learned how to program primarily from an OOP standpoint (like most of us, I'm sure), but I've spent a lot of time trying to learn how to solve problems the functional way. I have a good grasp on how to solve calculational problems with FP, but when it comes to more complicated problems I always find myself reverting to needing mutable objects. For example, if I'm writing a particle simulator, I will want particle "objects" with a mutable position to update. How are inherently "stateful" problems typically solved using functional programming techniques?</p>

答:
Subscribing to the right mental model helps one better think about and manage state.  In my mind, the best mental model is the flip book.  Once this clicks you'll understand that FP leans heavily on persistent data structures that capture the state of the world and that functions are used to transition that state without any mutation whatsoever.

Rich Hickey illuminates these ideas:

The Value of Values

The Database as a Value

There are other talks but this should send you in the right direction.


问:
What is a symbol in Ruby?
I'm totally new to the Ruby world, and I'm a bit confused with the concept of Symbols. What's the difference between Symbols and Variables? Why not just using variables?

Thanks.

答:
Symbol in Ruby is basically the same thing as symbol in real world. It is used to represent or name something.

Symbols are very commonly used to represent some kind of state, for example

```<code>order.status = :canceled
order.status = :confirmed
</code>```

You can also look at symbol as instant enum. You don't need to define a symbol, you just use it. This article explains it in great detail.

Title: What is a symbol in Ruby?

Body:
Symbol in Ruby is basically the same thing as symbol in real world. It is used to represent or name something.

Symbols are very commonly used to represent some kind of state, for example

order.status = :canceled
order.status = :confirmed

You can also look at symbol as instant enum. You don't need to define a symbol, you just use it. This article explains it in great detail.


答:
How about a flip book?

In a flip book each page represents the world as it exists at a moment in time.  In our program the world is represented as some compound data structure (e.g. we have a banana which is in the hand of a gorilla which is in a tree which is in a jungle).  Each subsequent page advances the story by slightly modifying the previous representation.  In FP, persistent data structures were designed to efficiently reuse previous structures so that a change provides only a delta and not a completely new rendition.

What may not be obvious is that a page in our flip book would also represent intangibles.  For example, if the gorilla drops the banana we might start applying the effects of gravity on its decent and acceleration toward the jungle floor.  To accommodate this we'd attach attributes such as velocity and trajectory to our banana.

In our program there would be a function that accepts a flip book page (a.k.a. the state of the world) as an argument and yields a new page.  In this manner our story is told without ever actually changing the state of existing objects.  We simply supersede each page with a newer one using what is effectively a calculation.


问:
Split up large interfaces
I'm using a large interface with about 50 methods to access a database. The interface has been written by a colleague of mine. We discussed this:

Me: 50 methods is too much. It's a code smell.

Colleague: What shall I do about it? You want the DB access - you have it.

Me: Yeah, but it's unclear and hardly maintainable in the future.

Colleague: OK, you are right, it's not nice. How should the interface look like then?

Me: How about 5 methods that return objects that have, like, 10 methods each?

Mmmh, but wouldn't this be the same? Does this really lead to more clarity? Is it worth the effort?

Every now and then I'm in a situation where I want an interface and the first thing that comes to mind is one, big interface. Is there a general design pattern for this?

Update (responding to SJuan's comment):

The "kind of methods": It's an interface for fetching data from a database. All methods have the form (pseudocode)

```<code>List<Typename> createTablenameList()
</code>```

Methods and tables are not exactly in a 1-1-relation, the emphasis is more on the fact that you always get some kind of list that comes from a database.

答:
Every now and then I'm in a situation where I want an interface and the first thing that comes to mind is one big interface. Is there a general design pattern for this?

It's a design anti-pattern called the monolithic class.  Having 50 methods in a class or interface is a probable violation of the SRP.  The monolithic class comes about because it tries to be everything to everyone.

DCI addresses method bloat.  Essentially the many responsibilities of a class could be apportioned to roles (offloaded to other classes) that are only relevant in certain contexts.  The application of roles can be achieved in a number of ways including mixins or decorators.  This approach keeps classes focused and lean.

How about 5 methods that return objects that have, like, 10 methods each?

This suggests instantiating all roles when the object is itself instantiated.  But why instantiate roles you might not need?  Instead, instantiate a role in the context in which you actually need it.

If you find that refactoring toward DCI is not obvious, you could go with a simpler visitor pattern.  It provides a similar benefit without emphasizing the creation of use case contexts.

EDIT: My thinking on this has changed some.  I provided an alternative answer.

Title: Split up large interfaces


答:
Yes, 50 methods is a code smell, but a code smell means to take a second look at it, not that it's automatically wrong.  If every client using that class potentially needs all 50 methods, there may not be a case to split it.  However, this is unlikely.  My point is, splitting an interface arbitrarily can be worse than not splitting it at all.

There isn't a single pattern to fix it, but the principle that describes the desired state is the Interface Segregation Principle (the 'I' in SOLID), which states that no client should be forced to depend on methods it doesn't use.

The ISP description does give you a hint on how to fix it:  look at the client.  Often, just by looking at a class it seems like everything belongs together, but clear divisions emerge when you look at the clients using that class.  Always consider the clients first when designing an interface.

The other way to determine if and where an interface should be split is by making a second implementation.  What often ends up happening is your second implementation doesn't need a lot of the methods, so those clearly should be split off into their own interface.

Title: Split up large interfaces