答:
Technically, you can resolve any cyclic dependency by using interfaces, as shown in the other answers. However, I recommend to rethink your design. I think it is not unlikely you can avoid the need for additional interfaces completely, while your design becomes even simpler.

I guess it is not necessary for a ReportGenerator to depend on a TestScenario directly. TestScenario seems to have two responsibilites: it is used for test execution, and it works also as a container for the results. This is a violation of the SRP. Interestingly, by resolving that violation, you will get rid of the cyclic dependency as well.

So instead of letting the report generator grab data from the test scenario, pass the data explicitly by using some value object. That means, replace

```<code>   reportGenerator.setTestScenario(ts);
</code>```

by some code like

```<code>reportGenerator.insertDataToDisplay(ts.getReportData());
</code>```

The method getReportData needs to have a return type like ReportData, a value object which works as a container for the data to be displayed in the report. insertDataToDisplay is a method which expects an object of exactly that type.

This way, ReportGenerator and TestScenario will both depend on ReportData, which depends on nothing else, and the first two classes do not depend on each other any more.

As a second approach: to resolve the SRP violation let TestScenario be responsible for holding the results of a test execution, but not for calling the test executer. Consider to reorganize the code so not the test scenario accesses the test executer, but the test executer is started from outside and writes the results back into the TestScenario object. In the example you showed us, that will be possible by making the access to LinkedList<Test> inside of TestScenario public, and by moving the execute method from TestScenario to somewhere else, maybe directly into a TestExecuter, maybe into a new class TestScenarioExecuter.

That way, TestExecuter will depend on TestScenario and ReportGenerator, ReportGenerator will depend on TestScenario, too , but TestScenario will depend on nothing else.

And finally, a third approach: TestExecuter has too many responsibilities, too. It is responsible for executing tests as well as for providing a TestScenario to a ReportGenerator. Put these two responsibilities into two separate classes, and your cyclic dependency will vanish again.

There may be more variants to approach your problem, but I hope you get the general idea: your core problem are classes with too many responsibilities. Solve that problem, and you will get rid of the cyclic dependency automatically.

Title: How to solve circular dependency?

Body:
I have three classes that are circular dependant to each other:

TestExecuter execute requests of TestScenario  and save a report file using ReportGenerator class.
So:

TestExecuter depends on ReportGenerator to generate the report

ReportGenerator depends on TestScenario and on parameters set from TestExecuter.

TestScenario depends on TestExecuter.

Can't figure out how to remove thoses dependencies.

public class TestExecuter {

  ReportGenerator reportGenerator;

  public void getReportGenerator() {
     reportGenerator = ReportGenerator.getInstance();
     reportGenerator.setParams(this.params);
     /* this.params several parameters from TestExecuter class example this.owner */
  }

  public void setTestScenario (TestScenario  ts) {
     reportGenerator.setTestScenario(ts);
  }

  public void saveReport() {
     reportGenerator.saveReport();
  }

  public void executeRequest() {
    /* do things */
  }
}
```

<pre class="lang-java prettyprint-override"><code>public class ReportGenerator{
    public static ReportGenerator getInstance(){}
    public void setParams(String params){}
    public void setTestScenario (TestScenario ts){}
    public void saveReport(){}
}
</code>```

public class TestScenario {

    TestExecuter testExecuter;

    public TestScenario(TestExecuter te) {
        this.testExecuter=te;
    }

    public void execute() {
        testExecuter.executeRequest();
    }
}
```

<pre class="lang-java prettyprint-override"><code>public class Main {
    public static void main(String [] args) {
      TestExecuter te = new TestExecuter();
      TestScenario ts = new TestScenario(te);

      ts.execute();
      te.getReportGenerator();
      te.setTestScenario(ts);
      te.saveReport()
    }
}
</code>```

EDIT: in response to an answer, more details about my TestScenario class:

public class TestScenario {
    private LinkedList<Test> testList;
    TestExecuter testExecuter;

    public TestScenario(TestExecuter te) {
        this.testExecuter=te;
    }

    public void execute() {
        for (Test test: testList) {
            testExecuter.executeRequest(test);
        }
    }
}

public class Test {
  private String testName;
  private String testResult;
}

public class ReportData {
/*shall have all information of the TestScenario including the list of Test */
    }
```

<p>An example of the xml file to be generated in case of a scenario containing two tests:</p>

<pre class="lang-java prettyprint-override"><code><testScenario name="scenario1">
   <test name="test1">
     <result>false</result>
   </test>
   <test name="test1">
     <result>true</result>
   </test>
</testScenario >
</code>```

Body:
Technically, you can resolve any cyclic dependency by using interfaces, as shown in the other answers. However, I recommend to rethink your design. I think it is not unlikely you can avoid the need for additional interfaces completely, while your design becomes even simpler.

I guess it is not necessary for a ReportGenerator to depend on a TestScenario directly. TestScenario seems to have two responsibilites: it is used for test execution, and it works also as a container for the results. This is a violation of the SRP. Interestingly, by resolving that violation, you will get rid of the cyclic dependency as well.

So instead of letting the report generator grab data from the test scenario, pass the data explicitly by using some value object. That means, replace

   reportGenerator.setTestScenario(ts);

by some code like

reportGenerator.insertDataToDisplay(ts.getReportData());

The method getReportData needs to have a return type like ReportData, a value object which works as a container for the data to be displayed in the report. insertDataToDisplay is a method which expects an object of exactly that type.

This way, ReportGenerator and TestScenario will both depend on ReportData, which depends on nothing else, and the first two classes do not depend on each other any more.

As a second approach: to resolve the SRP violation let TestScenario be responsible for holding the results of a test execution, but not for calling the test executer. Consider to reorganize the code so not the test scenario accesses the test executer, but the test executer is started from outside and writes the results back into the TestScenario object. In the example you showed us, that will be possible by making the access to LinkedList<Test> inside of TestScenario public, and by moving the execute method from TestScenario to somewhere else, maybe directly into a TestExecuter, maybe into a new class TestScenarioExecuter.

That way, TestExecuter will depend on TestScenario and ReportGenerator, ReportGenerator will depend on TestScenario, too , but TestScenario will depend on nothing else.

And finally, a third approach: TestExecuter has too many responsibilities, too. It is responsible for executing tests as well as for providing a TestScenario to a ReportGenerator. Put these two responsibilities into two separate classes, and your cyclic dependency will vanish again.

There may be more variants to approach your problem, but I hope you get the general idea: your core problem are classes with too many responsibilities. Solve that problem, and you will get rid of the cyclic dependency automatically.


问:
Is it ok to have multiple classes in the same file in Python?
I'm freshly coming to the Python world after years of Java and PHP. While the language itself is pretty much straightforward, I'm struggling with some 'minor' issues that I can't wrap my head around — and to which I couldn't find answers in the numerous documents and tutorials I've read this far.

To the experienced Python practitioner, this question might seem silly, but I really want an answer to it so I can go further with the language:

In Java and PHP (although not strictly required), you are expected to write each class on its own file, with file's name is that of the class as a best practice.

But in Python, or at least in the tutorials I've checked, it is ok to have multiple classes in the same file.

Does this rule hold in production, deployment-ready code or it's done just for the sake of brevity in educative-only code?

答:
When structuring your application in Python, you need to think in terms of packages and modules.

Modules are about the files you are talking about. It is fine to have a bunch of classes within the same module. The aim is that all the classes within the same module should serve the same purpose/logic. If the module goes too long then think of subdividing it by redesigning your logic.

Do not forget to read from time to time about Index of Python Enhancement Proposals.

ContentLicense: CC BY-SA 3.0


问:
Feeding events to Elasticsearch, do I really need Logstash?
I'm designing an analytics system that feeds all events to Elasticsearch. The event lifecycle is as follows:

Visitor does something.

Custom analytics server gathers data, makes an event out of it and puts it into Elasticsearch.

One a day or so, custom batch processor aggregates a large set of events from Elasticsearch, transforms them to smaller chunks of data and puts back to Elasticsearch.

I know Logstash is made to gather and process events. Why should I consider it over my own custom solution?

I have no log files in the process. Events travel from one component to another via HTTP. I don't care transforming the data to events on my own either.

I'm especially concerned about not having the flexibility of dealing with the events and Elasticsearch directly from my own choice of programming language.

答:
Of course you can use the ElasticSearch Index API directly: https://www.elastic.co/guide/en/elasticsearch/reference/1.4/docs-index_.html

Logstash's main responsibility in the ELK stack is the efficient collection and conversion of a stream of logs into individual, indexable documents. If you already have individual, indexable documents, Logstash may be an unnecessary complication.

When you have an existing stream of data that you want to index, Logstash provides a single endpoint for aggregating, parsing and enriching that data. When you want to change how you process or present a log, you make that change in Logstash -- not your application. This decoupling can allow an analytics team to efficiently manage an application that is slow to update, or that they don't control themselves. Logstash also acts as buffer, protecting ES' endpoints from thundering herd issues, though you can scale ES to diminish this problem.

Note that the enrichment is a very nice feature -- it can allow you to add additional context to your documents logs without rebuilding the services that produce them, or to remap fields to mate a canonical logging format.


答:
Is it ok to have multiple classes in the same file in Python?

Yes. Both from a philosophical perspective as well as a practical one.

In Python, modules are a namespace that exist once in memory.

Say we had the following hypothetical directory structure, with one class defined per file:

```<code>                    Defines
 abc/
 |-- callable.py    Callable
 |-- container.py   Container
 |-- hashable.py    Hashable
 |-- iterable.py    Iterable
 |-- iterator.py    Iterator
 |-- sized.py       Sized
 ... 19 more
</code>```

All of these classes are available in the collections module and (there are, in fact, 25 in total) defined in the standard library module in _collections_abc.py

There are a couple of issues here that I believe makes the _collections_abc.py superior to the alternative hypothetical directory structure.

These files are sorted alphabetically. You could sort them in other ways, but I am not aware of a feature that sorts files by semantic dependencies. The _collections_abc module source is organized by dependency.

In non-pathological cases, both modules and class definitions are singletons, occurring once each in memory. There would be a bijective mapping of modules onto classes - making the modules redundant.

The increasing number of files makes it less convenient to casually read through the classes (unless you have an IDE that makes it simple) - making it less accessible to people without tools.

Are you prevented from breaking groups of classes into different modules when you find it desirable from a namespacing and organizational perspective?

No.

From the Zen of Python , which reflects the philosophy and principles under which it grew and evolved:

Namespaces are one honking great idea -- let's do more of those!

But let us keep in mind that it also says:

Flat is better than nested.

Python is incredibly clean and easy to read. It encourages you to read it. Putting every separate class in a separate file discourages reading. This goes against the core philosophy of Python. Look at the structure of the Standard Library, the vast majority of modules are single-file modules, not packages. I would submit to you that idiomatic Python code is written in the same style as the CPython standard lib.

Here's the actual code from the abstract base class module. I like to use it as a reference for the denotation of various abstract types in the language.

Would you say that each of these classes should require a separate file?

```<code>class Hashable:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __hash__(self):
        return 0

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Hashable:
            try:
                for B in C.__mro__:
                    if "__hash__" in B.__dict__:
                        if B.__dict__["__hash__"]:
                            return True
                        break
            except AttributeError:
                # Old-style class
                if getattr(C, "__hash__", None):
                    return True
        return NotImplemented

class Iterable:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __iter__(self):
        while False:
            yield None

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Iterable:
            if _hasattr(C, "__iter__"):
                return True
        return NotImplemented

Iterable.register(str)

class Iterator(Iterable):

    @abstractmethod
    def next(self):
        'Return the next item from the iterator. When exhausted, raise StopIteration'
        raise StopIteration

    def __iter__(self):
        return self

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Iterator:
            if _hasattr(C, "next") and _hasattr(C, "__iter__"):
                return True
        return NotImplemented

class Sized:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __len__(self):
        return 0

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Sized:
            if _hasattr(C, "__len__"):
                return True
        return NotImplemented

class Container:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __contains__(self, x):
        return False

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Container:
            if _hasattr(C, "__contains__"):
                return True
        return NotImplemented

class Callable:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __call__(self, *args, **kwds):
        return False

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Callable:
            if _hasattr(C, "__call__"):
                return True
        return NotImplemented
</code>```

So should they each have their own file?

I hope not.

These files are not just code - they are documentation on the semantics of Python.

They are maybe 10 to 20 lines on average.  Why should I have to go to a completely separate file to see another 10 lines of code? That would be highly impractical. Further, there would be nearly identical boilerplate imports on each file, adding more redundant lines of code.

I find it quite useful to know that there is a single module where I can find all of these Abstract Base Classes, instead of having to look over a list of modules. Viewing them in context with each other allows me to better understand them. When I see that an Iterator is an Iterable, I can quickly review what an Iterable consists of by glancing up.

I sometimes wind up having a couple of very short classes. They stay in the file, even if they need to grow larger over time. Sometimes mature modules have over 1000 lines of code. But ctrl-f is easy, and some IDE's make it easy to view outlines of the file - so no matter how large the file, you can quickly go to whatever object or method that you're looking for.

Conclusion

My direction, in the context of Python, is to prefer to keep related and semantically similar class definitions in the same file. If the file grows so large as to become unwieldy, then consider a reorganization.

Body:
I'm freshly coming to the Python world after years of Java and PHP. While the language itself is pretty much straightforward, I'm struggling with some 'minor' issues that I can't wrap my head around — and to which I couldn't find answers in the numerous documents and tutorials I've read this far.

To the experienced Python practitioner, this question might seem silly, but I really want an answer to it so I can go further with the language:

In Java and PHP (although not strictly required), you are expected to write each class on its own file, with file's name is that of the class as a best practice.

But in Python, or at least in the tutorials I've checked, it is ok to have multiple classes in the same file.

Does this rule hold in production, deployment-ready code or it's done just for the sake of brevity in educative-only code?

Body:
Is it ok to have multiple classes in the same file in Python?

Yes. Both from a philosophical perspective as well as a practical one.

In Python, modules are a namespace that exist once in memory.

Say we had the following hypothetical directory structure, with one class defined per file:

                    Defines
 abc/
 |-- callable.py    Callable
 |-- container.py   Container
 |-- hashable.py    Hashable
 |-- iterable.py    Iterable
 |-- iterator.py    Iterator
 |-- sized.py       Sized
 ... 19 more

All of these classes are available in the collections module and (there are, in fact, 25 in total) defined in the standard library module in _collections_abc.py

There are a couple of issues here that I believe makes the _collections_abc.py superior to the alternative hypothetical directory structure.

These files are sorted alphabetically. You could sort them in other ways, but I am not aware of a feature that sorts files by semantic dependencies. The _collections_abc module source is organized by dependency.

In non-pathological cases, both modules and class definitions are singletons, occurring once each in memory. There would be a bijective mapping of modules onto classes - making the modules redundant.

The increasing number of files makes it less convenient to casually read through the classes (unless you have an IDE that makes it simple) - making it less accessible to people without tools.

Are you prevented from breaking groups of classes into different modules when you find it desirable from a namespacing and organizational perspective?

No.

From the Zen of Python , which reflects the philosophy and principles under which it grew and evolved:

Namespaces are one honking great idea -- let's do more of those!

But let us keep in mind that it also says:

Flat is better than nested.

Python is incredibly clean and easy to read. It encourages you to read it. Putting every separate class in a separate file discourages reading. This goes against the core philosophy of Python. Look at the structure of the Standard Library, the vast majority of modules are single-file modules, not packages. I would submit to you that idiomatic Python code is written in the same style as the CPython standard lib.

Here's the actual code from the abstract base class module. I like to use it as a reference for the denotation of various abstract types in the language.

Would you say that each of these classes should require a separate file?

class Hashable:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __hash__(self):
        return 0

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Hashable:
            try:
                for B in C.__mro__:
                    if "__hash__" in B.__dict__:
                        if B.__dict__["__hash__"]:
                            return True
                        break
            except AttributeError:
                # Old-style class
                if getattr(C, "__hash__", None):
                    return True
        return NotImplemented

class Iterable:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __iter__(self):
        while False:
            yield None

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Iterable:
            if _hasattr(C, "__iter__"):
                return True
        return NotImplemented

Iterable.register(str)

class Iterator(Iterable):

    @abstractmethod
    def next(self):
        'Return the next item from the iterator. When exhausted, raise StopIteration'
        raise StopIteration

    def __iter__(self):
        return self

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Iterator:
            if _hasattr(C, "next") and _hasattr(C, "__iter__"):
                return True
        return NotImplemented

class Sized:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __len__(self):
        return 0

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Sized:
            if _hasattr(C, "__len__"):
                return True
        return NotImplemented

class Container:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __contains__(self, x):
        return False

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Container:
            if _hasattr(C, "__contains__"):
                return True
        return NotImplemented

class Callable:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __call__(self, *args, **kwds):
        return False

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Callable:
            if _hasattr(C, "__call__"):
                return True
        return NotImplemented

So should they each have their own file?

I hope not.

These files are not just code - they are documentation on the semantics of Python.

They are maybe 10 to 20 lines on average.  Why should I have to go to a completely separate file to see another 10 lines of code? That would be highly impractical. Further, there would be nearly identical boilerplate imports on each file, adding more redundant lines of code.

I find it quite useful to know that there is a single module where I can find all of these Abstract Base Classes, instead of having to look over a list of modules. Viewing them in context with each other allows me to better understand them. When I see that an Iterator is an Iterable, I can quickly review what an Iterable consists of by glancing up.

I sometimes wind up having a couple of very short classes. They stay in the file, even if they need to grow larger over time. Sometimes mature modules have over 1000 lines of code. But ctrl-f is easy, and some IDE's make it easy to view outlines of the file - so no matter how large the file, you can quickly go to whatever object or method that you're looking for.

Conclusion

My direction, in the context of Python, is to prefer to keep related and semantically similar class definitions in the same file. If the file grows so large as to become unwieldy, then consider a reorganization.


问:
How to solve circular dependency?
I have three classes that are circular dependant to each other:

TestExecuter execute requests of TestScenario  and save a report file using ReportGenerator class.
So:

TestExecuter depends on ReportGenerator to generate the report

ReportGenerator depends on TestScenario and on parameters set from TestExecuter.

TestScenario depends on TestExecuter.

Can't figure out how to remove thoses dependencies.

public class TestExecuter {

  ReportGenerator reportGenerator;

  public void getReportGenerator() {
     reportGenerator = ReportGenerator.getInstance();
     reportGenerator.setParams(this.params);
     /* this.params several parameters from TestExecuter class example this.owner */
  }

  public void setTestScenario (TestScenario  ts) {
     reportGenerator.setTestScenario(ts);
  }

  public void saveReport() {
     reportGenerator.saveReport();
  }

  public void executeRequest() {
    /* do things */
  }
}
```

<pre class="lang-java prettyprint-override"><code>public class ReportGenerator{
    public static ReportGenerator getInstance(){}
    public void setParams(String params){}
    public void setTestScenario (TestScenario ts){}
    public void saveReport(){}
}
</code>```

public class TestScenario {

    TestExecuter testExecuter;

    public TestScenario(TestExecuter te) {
        this.testExecuter=te;
    }

    public void execute() {
        testExecuter.executeRequest();
    }
}
```

<pre class="lang-java prettyprint-override"><code>public class Main {
    public static void main(String [] args) {
      TestExecuter te = new TestExecuter();
      TestScenario ts = new TestScenario(te);

      ts.execute();
      te.getReportGenerator();
      te.setTestScenario(ts);
      te.saveReport()
    }
}
</code>```

EDIT: in response to an answer, more details about my TestScenario class:

public class TestScenario {
    private LinkedList<Test> testList;
    TestExecuter testExecuter;

    public TestScenario(TestExecuter te) {
        this.testExecuter=te;
    }

    public void execute() {
        for (Test test: testList) {
            testExecuter.executeRequest(test);
        }
    }
}

public class Test {
  private String testName;
  private String testResult;
}

public class ReportData {
/*shall have all information of the TestScenario including the list of Test */
    }
```

<p>An example of the xml file to be generated in case of a scenario containing two tests:</p>

<pre class="lang-java prettyprint-override"><code><testScenario name="scenario1">
   <test name="test1">
     <result>false</result>
   </test>
   <test name="test1">
     <result>true</result>
   </test>
</testScenario >
</code>```

答:
By using interfaces you can solve the circular dependency.

Current design:

Proposed design:

In the proposed design concrete classes don't depend on other concrete classes but only on abstractions (interfaces).

Important:

You have to use the creational pattern of your choice (maybe a factory) to avoid perfoming new of any concrete classes inside any other concrete class or calling getInstance(). Only the factory will have dependencies on concrete classes. Your Main class could serve as factory if you think a dedicated factory would be overkill. For example you can inject a ReportGenerator into TestExecuter instead of calling getInstance() or new.

Title: How to solve circular dependency?


问:
Annotate source code with diagrams as comments
I write a lot of (primarily c++ and javascript) code that touches upon computational geometry and graphics and those kinds of topics, so I have found that visual diagrams have been an indispensable part of the process of solving problems.

I have determined just now that "oh, wouldn't it just be fantastic if I could somehow attach a hand-drawn diagram to a piece of code as a comment", and this would allow me to come back to something I worked on, days, weeks, months earlier and far more quickly re-grok my algorithms.

As a visual learner, I feel like this has the potential to improve my productivity with almost every type of programming because simple diagrams can help with understanding and reasoning about any type of non-trivial data structure. Graphs for example. During graph theory class at university I had only ever been able to truly comprehend the graph relationships that I could actually draw diagrammatical representations of.

So...

No IDE to my knowledge lets you save a picture as a comment to code.

My thinking was that I or someone else could come up with some reasonably easy-to-use tool that can convert an image into a base64 binary string which I can then insert into my code.

If the conversion/insertion process can be streamlined enough it would allow a far better connection between the diagram and the actual code, so I no longer need to chronographically search through my notebooks. Even more awesome: plugins for the IDEs to automatically parse out and display the image. There is absolutely nothing difficult about this from a theoretical point of view.

My guess is that it would take some extra time for me to actually figure out how to extend my favorite IDEs and maintain these plugins, so I'd be totally happy with a sort of code post-processor which would do the same parsing out and rendering of the images and show them side by side with the code, inside of a browser or something. Since I'm a javascript programmer by trade.

What do people think? Would anyone pay for this? I would. But I would perhaps also point out that regardless of whether I or some significant number of my peers would pay for such a thing, the only way such a thing is likely to succeed would be through an open source release.

答:
What do people think? Would anyone pay for this? I would.

ZOMG, I fit in a similar category as you and would love such a feature directly in the IDE.

For now I just tend to do lots of ASCII "art" like this:

```<code>// ******************************************************
// *v3            |e5          v4*           |e6      v6*
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |p1        *
// *              |            e1*-----------~----------*
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *cen           |p0          v0*           |        v5*
// *--------------~--------------************************
// *e4            |              *           |e7        *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |p2        *
// *              |            e2*-----------~----------*
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *v2            |e3          v1*           |e8      v7*
// ******************************************************
</code>```

The main value I find is seeing the variable names corresponding to the visual diagram, especially when we're using complex traversals of meshes and such for new mesh algorithms. This doxygen graph-generating trick shown in one of the answers is super cool -- I should try that more.

There are so many things that are easier to communicate visually as well, not necessarily even using graphs. Example:

... or this (comparison of my algorithm I'm calling "hook subdivision" to standard CC subdivision as used by Pixar):

It would give the code so much context to just see what these operations do and how they differ inside the code because some things are just best shown visually. Pictures really can capture a thousand words.

So it would be totally dreamy to me to have an IDE that let me see code and images side-by-side, allowing me to embed images into the source code.

Especially when we're inventing new algorithms, it's hard to find a good way to describe them very accurately (from a technical perspective, not exactly user perspective) without going into their algorithmic steps since there's nothing to really compare them to directly. These kinds of before and after images tend to totally show what you can expect from the algorithm right away.

Another thing I dream about is a visual debugger that lets me program it so that I can make some of my data types output an image into the debugger, e.g., to see the results visually as I'm stepping through code and making sure the algorithms I'm trying to invent are working correctly at every step and matching up how I drew it up on paper. For example, make my mesh data structure output a rendered image in the debugger watch window -- ideal if I could even rotate the view and such right then and there.

Also when working in very large-scale codebases (tens of millions of LOC) written by loose teams with like a thousand plugins, sometimes it can be a nightmare just to figure out how to execute the code we're looking at for some obscure, rarely-used plugin from the UI. It would be so awesome in those cases if the code could embed a miniature screenshot showing how to actually invoke that code from the user interface (might be prone to get out of date from time to time, but usually UIs aren't so unstable across versions as to render former screenshots useless).

Would anyone pay for this? I would.

So anyway, yeah, totally! I want that!!!

Body:
What do people think? Would anyone pay for this? I would.

ZOMG, I fit in a similar category as you and would love such a feature directly in the IDE.

For now I just tend to do lots of ASCII "art" like this:

// ******************************************************
// *v3            |e5          v4*           |e6      v6*
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |p1        *
// *              |            e1*-----------~----------*
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *cen           |p0          v0*           |        v5*
// *--------------~--------------************************
// *e4            |              *           |e7        *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |p2        *
// *              |            e2*-----------~----------*
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *              |              *           |          *
// *v2            |e3          v1*           |e8      v7*
// ******************************************************

The main value I find is seeing the variable names corresponding to the visual diagram, especially when we're using complex traversals of meshes and such for new mesh algorithms. This doxygen graph-generating trick shown in one of the answers is super cool -- I should try that more.

There are so many things that are easier to communicate visually as well, not necessarily even using graphs. Example:

... or this (comparison of my algorithm I'm calling "hook subdivision" to standard CC subdivision as used by Pixar):

It would give the code so much context to just see what these operations do and how they differ inside the code because some things are just best shown visually. Pictures really can capture a thousand words.

So it would be totally dreamy to me to have an IDE that let me see code and images side-by-side, allowing me to embed images into the source code.

Especially when we're inventing new algorithms, it's hard to find a good way to describe them very accurately (from a technical perspective, not exactly user perspective) without going into their algorithmic steps since there's nothing to really compare them to directly. These kinds of before and after images tend to totally show what you can expect from the algorithm right away.

Another thing I dream about is a visual debugger that lets me program it so that I can make some of my data types output an image into the debugger, e.g., to see the results visually as I'm stepping through code and making sure the algorithms I'm trying to invent are working correctly at every step and matching up how I drew it up on paper. For example, make my mesh data structure output a rendered image in the debugger watch window -- ideal if I could even rotate the view and such right then and there.

Also when working in very large-scale codebases (tens of millions of LOC) written by loose teams with like a thousand plugins, sometimes it can be a nightmare just to figure out how to execute the code we're looking at for some obscure, rarely-used plugin from the UI. It would be so awesome in those cases if the code could embed a miniature screenshot showing how to actually invoke that code from the user interface (might be prone to get out of date from time to time, but usually UIs aren't so unstable across versions as to render former screenshots useless).

Would anyone pay for this? I would.

So anyway, yeah, totally! I want that!!!


问:
When to use weak references in .Net?
I have not personally come across a situation where I've needed to use WeakReference type in .Net, but the popular belief seems to be that it should be used in caches. Dr Jon Harrop gave a very good case against the use of WeakReferences in caches in his answer to this question.

I've also often heard AS3 developers talk about using weak references to save on memory footprint but based on the conversations I've had it seems to add complexity without necessarily accomplishing the intended goal, and the runtime behaviour is rather unpredictable. So much so that many simply give up on it and instead manage the memory usage more carefully/optimize their code to be less memory intensive (or making the trade-off of more CPU-cycles and smaller memory footprint).

Dr Jon Harrop also pointed out in his answer that the .Net weak references are not soft, and there's an aggressive collection of weak references at gen0. According to MSDN, long weak references gives you the potential to recreate an object, but the state of the object remains unpredictable.!

Given these characteristics, I can't think of a situation where weak references would be useful, perhaps someone could enlighten me?

答:
Like logical leaks which are really hard to track down while users just tend to notice that running your software for a long time tends to take more and more memory and get slower and slower until they restart? I don't.

Consider what happens if, when the user requests to remove application resource above, Thing2 fails to properly handle such an event under:

Pointers

Strong References

Weak References

... and under which one of these such a mistake would likely be caught during testing, and which one wouldn't and would fly under the radar like a stealth fighter bug. Shared ownership is, more often than most, a nonsensical idea.

OwnerDisplayName: theburningmonk

Title: When to use weak references in .Net?


答:
The real answer to this is general, and not dependent on the language that's used: What should be in a file does not primarily depend on how many classes it defines. It depends on logical connectedness, and on complexity. Period.

Thus, if you have a few very small classes that are highly interconnected, they should be bundled into the same file. You should split out a class if it's either not tightly connected to another class, or if its too complex to be included with another class.

That said, the one-class-per-file rule is usually a good heuristic. However, there are important exceptions: A small helper class that is really just the implementation detail of its sole user class should generally be bundled into that user class's file. Likewise, if you have three classes vector2, vector3, and vector4, there is likely little reason to implement them in separate files.

Title: Is it ok to have multiple classes in the same file in Python?


问:
Do I need Bower for front end dependencies when I am already using composer?
I use composer for PHP dependencies. I was under the impression that for front end dependencies I should use Bower. So, I installed Bower and loaded my FE dependencies (Bootstrap, jQuery) using that. I then manually symlink to the libraries as follows:

```<code>mypc:/var/www/myproject/public/js$ ls -l
total 8
lrwxrwxrwx 1 tom tom   67 Dec 23 07:29 bootstrap.min.js -> /var/www/myproject/bower_components/bootstrap/dist/js/bootstrap.min.js
lrwxrwxrwx 1 tom tom   58 Dec 23 07:29 jquery.min.js -> /var/www/myproject/bower_components/jquery/dist/jquery.min.js
</code>```

However, I notice that these are stored within a directory /bower_components just as composer dependencies are stored in /vendor. So now I have /bower_components and /vendor as well as /node_modules (for grunt and grunt plugins). So as all Bower does it bring down the repositories, upon which I need to link to them - can I not just use composer for front end libraries too?

```<code>"components/jquery": "dev-master"
"components/bootstrap": "dev-master"
</code>```

.. then create symlinks to the files (e.g. .js .css) in my public/* directories? Is there any reason whhy Bower is still better for managing FE dependencies? Thanks

答:
I just stumbled across this gem that will allow you to use Composer with Bower packages:

https://github.com/francoispluchino/composer-asset-plugin

From their Readme:

The Composer Asset Plugin allows you to manage project assets (css,
  js, etc.) in your composer.json without installing NPM or Bower.

This plugin works by transposing package information from NPM or Bower
  to a compatible version for Composer. This allows you to manage asset
  dependencies in a PHP based project very easily.

  Features include:

Works with native management system versions of VCS repository of composer

Works with public and private VCS repositories

Lazy loader of asset package definitions to improve performance

Import filter with the dependencies of the root package and the installed packages, for increased dramatically the performance for the
  update

Automatically get and create an Asset VCS repository defined in:

NPM Registry

Bower Registry

Automatically get and create the Asset VCS repositories of dependencies defined   in each asset package (dev dependencies
  included)

Mapping conversion of asset package to composer package for:

NPM Package - package.json

Bower Package - bower.json

Conversion of Semver version to the composer
  version

Conversion of Semver range version to the
  composer range version

Conversion of dependencies with URL to the
  composer dependencies with the creation of VCS repositories

Conversion of multiple versions of the same dependency
  to different dependencies of composer

Add manually the multiple versions of a same dependency in the project

Add a custom config of VCS Repository

Override the config of VCS Repository
  defined by the asset registry directly in extra section of root
  composer

VCS drivers for:

Git

GitHub (compatible with repository redirects)

Git Bitbucket

Mercurial

Mercurial Bitbucket

SVN

Perforce

Local cache system for:

package versions

package contents

repository redirects

Custom asset installers configurable in the root file composer.json

For Bower, all files defined in the section ignore will not be installed

Disable or replace the deleting of the ignore files for Bower

Enable manually the deleting of the ignore files for NPM

Use the Ignore Files Manager in the Composer scripts

Compatible with all commands, including:

depends

diagnose

licenses

remove

require

search (bower only)

show

status


答:
A very illustrative example of weak references used to good effect is the ConditionalWeakTable, which is used by the DLR (among other places) to attach additional "members" to objects.

You don't want the table to keep the object alive. This concept simply could not work without weak references.

But it kind of seems to me that all the uses for weak references came long after they were added to the language, since weak references have been part of .NET since version 1.1. It just seems like something you'd want to add, so that the lack of deterministic destruction won't back you into a corner as far as language features are concerned.

Title: When to use weak references in .Net?

Body:
I have not personally come across a situation where I've needed to use WeakReference type in .Net, but the popular belief seems to be that it should be used in caches. Dr Jon Harrop gave a very good case against the use of WeakReferences in caches in his answer to this question.

I've also often heard AS3 developers talk about using weak references to save on memory footprint but based on the conversations I've had it seems to add complexity without necessarily accomplishing the intended goal, and the runtime behaviour is rather unpredictable. So much so that many simply give up on it and instead manage the memory usage more carefully/optimize their code to be less memory intensive (or making the trade-off of more CPU-cycles and smaller memory footprint).

Dr Jon Harrop also pointed out in his answer that the .Net weak references are not soft, and there's an aggressive collection of weak references at gen0. According to MSDN, long weak references gives you the potential to recreate an object, but the state of the object remains unpredictable.!

Given these characteristics, I can't think of a situation where weak references would be useful, perhaps someone could enlighten me?


问:
Overriding Equals in an unbrittle way
I have a class WorkflowItemSearchCriteria whose instances represent a set of values and references that will be used to return a filtered result set of workflow items based on the given search criteria.

```<code>class WorkflowItemSearchCriteria
{
    string ID { get; set; }
    Client TargetClient { get; set; }
    Person Supervisor { get; set; }
    Person WorkingAttorney { get; set; }
    SearchDateKind? TargetSearchDateKind { get; set; }
    DateTime? FromDate { get; set; }
    DateTime? ToDate { get; set; }

    public override bool Equals(object obj)
    {
        if (!(obj is WorkflowItemSearchCriteria)) return false;
        var target = (WorkflowItemSearchCriteria) obj;
        if (!target.ID.Equals(this.ID)) return false;
        if (target.TargetClient != this.TargetClient) return false;
        if (target.Supervisor != this.Supervisor) return false;
        if (target.WorkingAttorney != this.WorkingAttorney) return false;
        if (!target.TargetSearchDateKind.Equals(this.TargetSearchDateKind)) return false;
        if (!target.FromDate.Equals(this.FromDate)) return false;
        if (!target.ToDate.Equals(this.ToDate)) return false;
        return true;
    }

    public override int GetHashCode()
    {
        // According to MSDN, two objects that are equal must return the same hash code,
        // but the same hash code does not mean two objects are equal.  If two value
        // objects are equal, then all property and field values must be equal,
        // so it's sufficient to return the hash code from just ONE field or property
        // because it will equal the hash code from another object that is equal to it.
        return ID.GetHashCode();
    }

    enum SearchDateKind
    {
        DateCreated,
        DateCompleted
    }
}
</code>```

At some point, I want to compare two instances of this class for value-wise equality, so I'm overriding Equals as shown.  I've been reading sources such as this to help me along, but I still feel that doing it the way I have results in brittle code because future developers would have to remember to update the Equals overload if there were ever properties added to WorkflowItemSearchCriteria.

Is there a better approach to this?

答:
I'm a little lacking on sleep at the moment, so I'm going to give a rough answer.

You can annotate equality-relevant members with a custom attribute of your own, such as [EqualityMember], and in the Equals method you can perform the comparisons using reflection. You would have to scan the type for fields/other members decorated with the attribute using GetCustomAttribute<EqualityMember>() != null.

You could even go crazier, and have the attribute specify how to approach the equality. What kind of comparison to use. Attributes are really neat.

Since type members aren't going to change, you can cache a lot of the reflection work and reuse it. I doubt performance will be a problem, but you could even construct an expression tree and compile it, though that sounds like a headache.

I've just realized, I've actually done this before. But I don't remember when or why...

Title: Overriding Equals in an unbrittle way


问:
What's the best practice for adding a lot of attributes to a Rails model?
So, I'm building an API wrapper gem that works with Spree's Product model. The API provides extensive customization of the data you send to it. I would like a user of the gem to be able to take advantage of all the customizations should they desire to. This appears to me as if I should create a migration that adds about 50 new attributes to the Product model in order to allow the user to customize these attributes for a product.

It feels awfully invasive for me to add 50 attributes to a model in which only a few may be used by any given user (it would be an edge case for someone to use most/all of them). What's the best practice for offering these attributes to the user without muddying up the main model.

My thought may have been to create another model that belongs to the Product and contains the API attributes, but this seems like it may create technical overhead.

For example:

```<code>class Spree::Product
  has_one :spree_product_api_attribute_set
  delegate :attr1, :attr2, :attr3..., to: :spree_product_api_attribute_set
end
</code>```

答: If you use Postgres, HStore or JSON can store key values pretty easily. You can still use indexes to query the DB. If there were 50 attributes that is what I would use. Far superior to serialized fields.</p>


问:
How to prevent user from requesting API method multiple times in parallel?
Let's say we have an app where the users gain points and can exchange them for rewards. The exchange request, in pseudo-code, could look like this:

```<code>function exchangePointsForReward(userId, rewardId){
    user = getUser(userId)
    reward = getReward(rewardId)
    if (user.points >= reward.requiredPoints){
        giveRewardToUser(userId, rewardId)
        reduceUserPoints(userId, reward.requiredPoints)
    }
}
</code>```

But if we have a malicious user what stops them from crafting a request in their favorite programming language and sending it 20 times at the same time? Before the first request reaches reduceUserPoints() ten other might've already got as far as addNewReward(). Sure, the user's points at the end of the day might go deep into negative, but what stops the user from quickly grabbing the rewards and using them up? How can I ensure that only one operation can be executed for a user at the same time?

One solution I can think of is the operation tries to acquire a lock at the beginning of the operation and only a single lockable operation can run for a user at any moment:

```<code>function aquireLock(userId){
    lockId = getRandomLockId()
    database.query("UPDATE user SET lock={lockId} WHERE user={userId} AND lock IS NULL");
    return database.query("SELECT lock WHERE user = {userId}").first === lockId;
}

function exchangePointsForReward(userId, rewardId){
    if (!aquireLock(userId)){
        throw new Error("Failed to acquire lock");
    }
    user = getUser(userId)
    reward = getReward(rewardId)
    if (user.points >= reward.requiredPoints){
        giveRewardToUser(userId, rewardId)
        reduceUserPoints(userId, reward.requiredPoints)
    }
    releaseLock(userId);
}
</code>```

But is there any better strategy here? The question is database-agnostic.

答:
You could use an optimistic approach.  Most databases use some sort of row versioning mechanism.  For example, in SQL Server...

https://msdn.microsoft.com/en-us/library/ms182776.aspx

So, every request gets the row version sent back to them if they wish to update the data.  The update then uses that row version as part of the update.  If the row version don't match, you know that someone else has updated the record previously and you can reject it (not perform the update).  Just note, that the row version doesn't make a good key candidate so some other data point should be used for the search and them compare the row version after the data is returned.  So, if there are multiple reads, only 1 subsequent update wins.

This can all be done is a simple stored procedure that queries and updates and you can use database transactions to manage the 'lock' since the row version is updated atomically.

Pessimistic locking will also work, but your taking out a lock for every transaction, which is probably overkill for the the normal use case.


答:
I'd require that to run the next operation the user must pass a token returned by a previous operation.

Imagine that you have a table of issued tokens (opaque random numbers). Once a user successfully runs a request, a new token is inserted into the table, and returned to the user.

You can serialize access to marking a token 'redeemed', so that it is guaranteed that a token can only be redeemed if it is still new; then the points are gained by the user. An attempt to redeem an already redeemed token, or an unknown token, results in an error, and the points are not counted.

Even if a user runs several requests in parallel, each request can only carry the same unredeemed token, and only one of the requests will succeed, since redeeming is serialized.

Periodically old redeemed tokens and excessively old unredeemed tokens are removed from the table.

If a user passes an incorrect token, points are not gained, but a new valid token is returned to the user in the reply. This way new clients, or clients that lost sync, can reconnect to the sequence.

The problem, of course, is in the serialized update. But if you only lock a record corresponding to a token, and not the whole table, many requests can be served in parallel.

Title: How to prevent user from requesting API method multiple times in parallel?

Body:
Let's say we have an app where the users gain points and can exchange them for rewards. The exchange request, in pseudo-code, could look like this:

```<code>function exchangePointsForReward(userId, rewardId){
    user = getUser(userId)
    reward = getReward(rewardId)
    if (user.points >= reward.requiredPoints){
        giveRewardToUser(userId, rewardId)
        reduceUserPoints(userId, reward.requiredPoints)
    }
}
</code>```

But if we have a malicious user what stops them from crafting a request in their favorite programming language and sending it 20 times at the same time? Before the first request reaches reduceUserPoints() ten other might've already got as far as addNewReward(). Sure, the user's points at the end of the day might go deep into negative, but what stops the user from quickly grabbing the rewards and using them up? How can I ensure that only one operation can be executed for a user at the same time?

One solution I can think of is the operation tries to acquire a lock at the beginning of the operation and only a single lockable operation can run for a user at any moment:

```<code>function aquireLock(userId){
    lockId = getRandomLockId()
    database.query("UPDATE user SET lock={lockId} WHERE user={userId} AND lock IS NULL");
    return database.query("SELECT lock WHERE user = {userId}").first === lockId;
}

function exchangePointsForReward(userId, rewardId){
    if (!aquireLock(userId)){
        throw new Error("Failed to acquire lock");
    }
    user = getUser(userId)
    reward = getReward(rewardId)
    if (user.points >= reward.requiredPoints){
        giveRewardToUser(userId, rewardId)
        reduceUserPoints(userId, reward.requiredPoints)
    }
    releaseLock(userId);
}
</code>```

But is there any better strategy here? The question is database-agnostic.


问:
When is a circular reference to a parent pointer acceptable?
This Stack Overflow question is about a child having reference to its parent, through a pointer.

Comments were pretty critical initially of the design being a horrible idea.

I understand this is probably not the best idea in general. From a general rule of thumb it seems fair to say, "don't do this!"

However, I am wondering what sorts of conditions would exist where you would need to do something like this. This question here and associated answers/commentary suggests even for graphs to not do something like this.

答:
Usually, circular references are a very bad idea because they mean circular dependencies. You probably already know why circular depedencies are bad, but for completeness' sake, the tl;dr version is that whenever classes A and B both depend on each other, it's impossible to understand/fix/optimize/etc either A or B without also understanding/fixing/optimizing/etc the other class at the same time. Which quickly leads to codebases where you can't change anything without changing everything.

However, it is possible to have a circular reference without creating evil circular dependencies. This works as long as the reference is strictly optional in a functional sense. By that I mean you could easily remove it from the classes and they would still work, even if they happen to work slower. The main use case I'm aware of for such circular non-dependency-creating references is enabling quick traversal of node-based data structures such as linked lists, trees and heaps. For instance, in principle any operation you can perform on a doubly-linked list you can also perform on a singly-linked list, there just happen to be a few operations (like moving backwards through the list) that have a much better big-O with the doubly-linked version.


答:
The key here is not whether two objects have circular references, but whether those references indicate ownership of each other.

Two objects cannot "own" each other: this causes an intractable dilemma for initialization and deletion order. One must be an optional reference, or otherwise indicate that one object will not manage the other's lifetime.

Consider a doubly-linked list: two nodes link back and forth to each other, but neither "owns" the other (the list owns them both). This means neither node allocates memory for the other or is otherwise responsible for the identity or lifetime management of the other.

Trees have a similar relationship, although nodes in a tree may allocate children and parents do own children. The link from a child to parent helps with traversal, but again does not define ownership.

In most OO designs, a reference to another object as an object's data member implies ownership. For example, suppose we have classes Car and Engine. Neither one is very useful on its own. We can say that these objects depend on each other: they require the presence of the other in order to perform useful work. But which "owns" the other? In this case we would say that Car owns Engine because the car is the "container" in which all of the automotive components live. In both an OO and real-world design, the car is the sum of its parts, and all of those parts are connected together within the context of the car. Engine may have a reference back to Car, or it may have a reference to TorqueConverter, but no component inside of Car owns Car even if said component has a reference to the Car.

Circular references can be a bad design smell, but not necessarily. When used judiciously and documented correctly, they can make using data structures easier.

Try traversing a tree without references going both ways between parents and children. Sure, you could come up with a stack-based approach that is brittle and complex, or you could use the reference-based approach that is trivially simple.

Title: When is a circular reference to a parent pointer acceptable?

Body:
This Stack Overflow question is about a child having reference to its parent, through a pointer.

Comments were pretty critical initially of the design being a horrible idea.

I understand this is probably not the best idea in general. From a general rule of thumb it seems fair to say, "don't do this!"

However, I am wondering what sorts of conditions would exist where you would need to do something like this. This question here and associated answers/commentary suggests even for graphs to not do something like this.


问:
C# .NET MVVM software architecture and naming conventions
I am currently working on a software using C# .NET and WPF with the MVVM pattern.

Though the software is almost done, I have been discussing our architecture for a long time and I would like to get your opinions/advices on the convention/good practices side.

The current architecture is as follows:

Project/

DataContext/

Models/

Engine3D/

...

Utilities/

Converters/

Statics/

ViewModels/

Grids/

Menus/

Windows/

...

Views/

Grids/

Menus/

Windows/

...

Models folder:

Contains the Models from the MVVM pattern.

The Models folder is organized by feature, meaning that it has nested folders named after a feature or context, for example Models/Engine3D for every Model related to 3D.

We never append the "Model" word as a suffix, the files are named [Feature].cs
For example, Project.cs, Model3D.cs, Animation.cs, etc...

Views folder:

Contains the Views from the MVVM pattern.

The Views folder is organized by WPF Control, meaning that it has nested folders named after a WPF Control, for example Views/Windows for every View related to a WPF Window, or View/Grids, etc...

The files are named [Feature][ControlType].xaml with:

[Feature]: The "feature" implemented/described by the View, for example "CreateProject" for a feature creating a Project, Display3DModel for a Grid displaying a Model3D (using 3D libraries), etc...

[ControlType]: The type of "xaml" control represented by the file, being a Window, a UserControl, a Grid, etc... As an example, a Window displaying the System Preferences would be called SystemPreferencesWindow.xaml, and a Grid holding the list of all the Projects would be ProjectsListGrid.xaml.
For example, CreateProjectWindow.xaml, SystemPreferencesWindow.xaml, Display3DModelGrid.xaml, ProjectsListGrid.xaml

ViewModels folder:

Contains the ViewModels from the MVVM pattern.

The ViewModels folder copies the Views folder in terms of architecture, meaning that it has nested folders named after a WPF Control, for example ViewModels/Windows for every ViewModel related to a WPF Window, or ViewModels/Grids.

A ViewModel file has the same name as its related View file, with the suffix "ViewModel": the files are named [Feature][ControlType]ViewModel.cs with:

For example, based on View => ViewModel:
CreateProjectWindow.xaml => CreateProjectWindowViewModel.cs, OpenProjectWindow.xaml => OpenProjectWindowViewModel.cs, etc...

DataContext folder:

Contains the DataContext files, ie. files related to a certain context in the software; these are classes that are neither ViewModels or Models, are mostly accessible "staticly" and correspond to a very specific context in the software execution flow so don't really belong in the Utilities folder.
These classes are for example the Session class holding session values concerning the user like the web technologies' sessions.

Utilities folder:

Contains a set of files/classes tools of various goals :

Definition classes, giving system mechanisms to the overall software such as ObservableObject.cs, DelegateCommand.cs and RelayCommand.cs which permit MVVM data binding, etc...

Utilities/Converters folder: Converters classes...

Utilities/Statices folder: Contains static operations classes taking an input and returning an output, for example FileOperations.cs, XWindow.cs (don't bother with the name, it's project's specific) that regroups System.Windows operations like InvokeWindow() and CloseWindow() so that it's easier to manipulate System.Windows in the code, Model3DImporter.cs which imports 3D Models very easily, SerializationManager.cs for serialization operations, etc...

Classes with constants:

Some classes need constants values and since these values must be accessed from pretty much everywhere in the code, we didn't store these constant values in the related classes but in a "sister" class.

These "sister" classes are as follows:

```<code>// The sister class
public static class Model3DConstants
{
    private static readonly IList<String> supportedFileExtensions = ...
}

// The original class
public class Model3D
{
}
</code>```

As I mentioned in the beginning of my message, I would like your ideas/advices on our architecture/naming conventions, because I am sure that we are missing something out but don't know what.

Are we doing the complete opposite of what should be done in a correct C# .NET MVVM software using WPF, what are the flaws and/or stuff that we should modify

Do not hesitate to participate in the debate neither or even ask me questions if I am unclear about the above description.

答:
The structure of a project should reflect the purpose and intend of the project.

From you question, and from your project structure, I have no idea what the purpose and intend of your project is.  But if would shed some light on what the project is about I am sure I can give some suggestions for a directory structure.

By having a Views directory, a ViewModels directory and a Models directory, you are organizing your code according to the roles of classes in the MVVM pattern.  This structure by design pattern makes your project look like an example project in how to use the MVVM pattern.

A project should be modular.

Unfortunately, the roles-in-a-design-pattern structure prevents modularity, i.e. you can't have AwesomeModel, AwesomeView and AwesomeViewModel together in an Awesome directory (and what if you needed a special AwesomeCollection class too?).

A project structure should scale.

For a project structure to scale it should allow for the project to have more classes without appearing more messy.  A ViewModels directory with 20 view-models in it is a mess, so this also speaks against the roles-in-a-design-pattern structure.

A scalable project structure cannot be a static bunch of directories.

However, putting away the generic details into some Shared, Common or Utilities directory greatly helps.  Have your home-grown frameworks there.  Should you end up having 10 or more subdirectories in the Utilities directory, so be it, at least they don't clutter the root directory.  Try not to overdo this, because what goes into the Utilities directory is what becomes the hardest to get rid of.  While some utility class matures to be used in more than one application, it might as well move in with it's initial application.


问:
Should I use a unit testing framework to validate XML documents?
From http://www.w3.org/XML/Schema:

[XML Schemas] provide a means for defining the structure, content and semantics of XML documents.

I'm using an XML Schema (XSD) to validate several large XML documents. While I'm finding plenty of support within XSD for checking the structure of my documents, there are no procedural if/else features that allow me to say, for instance,

If Country is USA, then Zipcode cannot be empty.

I'm comfortable using unit testing frameworks, and could quite happily use a framework to test content integrity.

Am I asking for trouble doing it this way, rather than an alternative approach? Has anybody tried this with good / bad results?

--

Edit: I didn't include this information to keep it technology agnostic, but I would be using C# / Linq / xUnit for deserialization / testing.

答:
XSD 2.0 has introduced assertions that actually function as if/then's. You would be able to build this "if country is USA then zip code cannot be blank". But it was indeed missing before.

While this is an old thread, I don't know if my reply is still relevant.


答:
The reason it's usually not a good idea to do this is because it violates the Dependency Inversion Principle.  People have written a lot about this in much more detail than I can cover adequately in this post, but it boils down to making it difficult to maintain, because the coupling is so tight.  Changing either class almost always necessitates a change in the other, whereas if the dependencies only point one way, changes on one side of the interface are isolated.  If both classes point to an abstract interface, even better.

The one main exception is when you don't have two different classes at different abstraction levels, but two nodes of the same class, such as in a tree, a doubly-linked list, etc.  Here it's more of a structural relationship than an abstraction relationship.  Circular references for the sake of algorithmic efficiency are acceptable and even encouraged in these sorts of cases.


答:
There are several aspects to consider in such a design:

the structural dependencies

the ownership relation (i.e.composition vs. other kind of associaton)

the navigation needs

Structural dependency between classes:

If you aim at reusing component classes, you should avoid unnecessary dependency and avoid such closed circular structures.

Nevertheless sometimes two classes are conceptually strongly interlinked. In this case, avoiding dependency is not a real option. Example: a tree and its leafes, or more generally a composite and its components.

Ownership of objects:

Does one object owns the other ? Or otherwise stated: if one object is destroyed, shall the other be destroyed as well ?

THis topic was addressed in depth by Snowman, so I'll not going to address it here.

Navigation needs between objects:

A last issue is navigation need.  Let's take my favourite example, the composite design pattern of the Gang of four.

Gamma & al. explictely mention the potential need to have an explicit parent reference: "Maintaining reference from child componenents to their parent can simplify traversal and management of a composite structure" Of course you could imagine a systematic top-down traversal, but for very large composite objects it can significantly slow down the operations and in an exponential manner. A direct reference, even circular can significantly ease manipulation of your composites.

An example could be a graphical model of an electronic system. A composite structure could represent the electronic boards, circuits, elements. To display and manipulate the model, you'd need some geometrical proxies in a GUI view.  It is then certainly much easier to navigate from the GUI element selected by the user to the component, to find out which is the parent and with are the related brother/sister elements, than to start a top down search.

Of course, as Gamma & al pointed out, you have to ensure the invarients of the circular relationship.  This can be tricky, as the SO question you refer to has shown. But it's perfectly manageable and in a safe manner.

Conclusion

The navigation need shall not be understimated.  It is not without reason that UML has explicitely adressed it in the modelling notation.  And yes, there are perfectly valid situation where circular references are needed.

The only point is that sometimes people tend to go into such a direction to quickly.  So it's worth to consider all the 3 aspects involved before taking the decision to go for it or not.


问:
Convention for exception argument order
Just a quick question about a design pattern for creating custom exceptions. The question is more about the order of parameters. If you can specify more data in the exception, should the parameter for it included in the constructor, come before or after the overload parameters?

Before:

```<code>public FooException : Exception
{
    public string Bar { get; private set; }

    public FooException(string bar) : base()
    {
        this.Bar = bar;
    }

    public FooException(string bar, string message) : base(message)
    {
        this.Bar = bar;
    }

    public FooException(string bar, string message, Exception inner) : base(message, inner)
    {
        this.Bar = bar;
    }
}
</code>```

After:

```<code>public FooException : Exception
{
    public string Bar { get; private set; }

    public FooException(string bar) : base()
    {
        this.Bar = bar;
    }

    public FooException(string message, string bar) : base(message)
    {
        this.Bar = bar;
    }

    public FooException(string message, Exception inner, string bar) : base(message, inner)
    {
        this.Bar = bar;
    }
}
</code>```

答: In general, not just for exceptions, you add additional parameters to the right of the signature when doing overloads. Reference</p>

Title: Convention for exception argument order


问:
Handle publishing data across environments
I am rewriting a website that has a back-end database for containing meta-data that is displayed to the user when they enter a text code.

Background:

The old/existing system stored this data in XML files with a master index XML file that pointed the correct data file based on a GUID. The way this is currently handled for publishing to production is all changes are done in a "staging" environment with the files being stored on Cloudfront under a "staging" folder. When they want to push changes to production, they simply copy the file from "staging" to "production".

I have updated the system to use a RDB (Postgres locally and it will be Aurora on AWS for production). I am using Java for the API with JPA annotations and Spring Boot. I have a separate Java Admin UI App that manages the meta-data and a separate user-facing application that is the website in Angular. The product owner still wants to be able to test changes in lower environments before publishing them to production.

Question:

I was trying to find a solution for publishing and was thinking that I may just have a staging env and a production env. A coworker here said that maybe have the Staging Admin App normally point to the Staging API, but when publishing, have it point to the Production API instead and not have a production Admin App. The problem I am running into is primary keys. You cannot specify the primary key in JPA AND have it auto-generated if it doesn't exist. I tried several different ways to do that and it breaks if I try to insert 1, 3, 2.

Does anybody have any recommendations on how to handle this situation? Transfer data from one RDB to another RDB in a different env while keeping all relationships intact.

答: Could you solve this using a DevOps solutions, rather than code? If you separate content out from other data you are storing, you could use the power of the cloud to take a snapshot of your content database, then make it available to your production instance, using the AWS API SDK. You could then have it update the connection string in your production app for it's content DB. That would also make rolling forward and backward easy, as you could go back to the old content DB if something went awry for any reason.</p>


问:
Role of Quality Assurance (Not testing!) in Agile
From Wikipedia:

Quality Assurance refers to administrative and procedural activities
implemented in a quality system so that requirements and goals for a
product, service or activity will be fulfilled.[1] It is the
systematic measurement, comparison with a standard, monitoring of
processes and an associated feedback loop that confers error
prevention.[2] This can be contrasted with quality control, which is
focused on process output.

You can read the following article to understand the difference between QA and testing (quality control): Link

What I'd like to understand is whether there is a place for QA engineer who is not a tester in Agile/Scrum. Agile is deliberately short on processes and documentation (its even in the manifesto), and that's what QA specialize in. So should there even be a QA engineer in Agile?

I myself am not a QA engineer (I am a test lead), but I have a friend who is, so that's why I am asking.

答:
If you read the publications of the founders of the quality movement (Shewart, Demming, Juran) you will quickly come to the realization that quality is an economic issue.  Lack of quality means there is a lot of waste.  Quality improvement is the process of driving waste out of the process.  Shewart, Demming and Juran were dealing with manufacturing but the same idea applies to software development.  In software development the primary source of waste is rework (fixing errors, retesting, redeploying) always assuming that the customers functional requirements were met.  The next most expensive problem is not producing something the customer wants to buy.  Software quality also involves the user.  Poor design or lack of reliability can increase the cost of using the software.

The role of Quality Assurance is not to test the product although test data is of use if it is recorded properly.  The role of quality assurance is to investigate possible ways of reducing the number of problems introduced and reducing the cost of correcting them.  This is not limited to code defects.

One of the worst processes for conduction any engineering development is to make designers/developers responsible for features.  The problems arise when more than one developer or team has to modify the same component to provide the desired functionality.  The result is defects that are not discovered until after integration (i.e. in system level testing).  In the ideal situation, system testing should not find any defects at all.  If a significant number are found, it means that there are a huge number of defects remaining in the product even after all the testing is done.  This results in an unreliable product.

The answer to this problem is component or subsystem based development in which only one developer or team may modify any given component of subsystem.  In a feature oriented shop, the role of the QA people would be to help the teams transition to a subsystem oriented process.

In any other undertaking, metrics are collected and used to predict the future.  In many software shops the key metric is either defects found or defects open.  But this is a useless metric for improvement.  The key metric is the number of defects still in the work products.  Requirements defects (assuming there are requirements) end up in the design along with the errors made producing the design.  Design defects (assuming there is a design) end up in the code along with the coding errors.  Quality Assurance should help to find ways of minimizing the number of defects carried over from previous work products by using the metrics collected when these items are produced and verified.

Quality Assurance is not responsible for the quality of the products.  The people who produce them are responsible.  Quality Assurance is responsible for discovering the messes made along the way and pointing them out to management so they can be addressed before they become serious and costly issues.

ContentLicense: CC BY-SA 4.0


问:
Resource representations and REST API documentation tools
I find myself unsure about what exactly it means to have different representations of a RESTful resource.  The canonical example is for an API to provide an endpoint - say /v1/users/:id - and allow the client to select the best representation of the resource between JSON, XML, HTML or PDF depending on the media range value of the ACCEPT headers.

I was under the impression that this definition of representation could be extended to encompass more than just content-types, but actually response schemas.  Say for example a client wants extended information about the user they could get it by specifying a supported header.

So for instance, my application could supply different schemas for the same resource i.e.

```<code># get the default user representation
GET /v1/users/1234
ACCEPT: application/vnd.myapp.v1+json

# server responds with
{"id": 1234, "name": "Jeffery Lebowski"}

# get the extended user representation
GET /v1/users/1234
ACCEPT: application/vnd.myapp.v1.extended+json

# server responds with
{"id": 1234, "name": "Jeffery Lebowski", "sport": "Bowling"}
</code>```

Am I correctly understanding the concept of representations in REST?  Or is the concept of resource representations only applicable to content types and content negotiation?

If so, how can I document the various representations that my API can return? It doesn't seem like either of the big documentation tools (swagger.io or RAML) support documenting multiple schema representations of a single resource.

答:
https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_2_1_2

You are exactly right in your understanding about representations, AND the RESTful way for you to get those different representation of one same is by doing content negotiation, using a standardised media type between the client and the server.

In HTTP, the standard way to do representation/content negotiation is by using the ACCEPT header (RFC 7231#section-5.3.2), with the standardised media ranges (RFC 6838#section-4.2).

I do think media type schemas, using the facets "." and suffix "+" part of the media type naming scheme should allowed and encouraged. That extension you did, IMHO it's also the right and pragmatic way to do it.

RAML does support multiple representations:

```<code>#%RAML 0.8
title: REST Content Negotiation Example
version: 0.1
baseUri: http://example.com

/v1/users/:
  displayName: users
  /{id}:
    displayName: id
    uriParameters:
      id:
        type: integer
    get:
      responses:
        200:
          body:
            application/vnd.myapp.v1+json:
              example: |
                {"id": 1234, "name": "Jeffery Lebowski"}

            application/vnd.myapp.v1.extended+json:
              example: |
                {"id": 1234, "name": "Jeffery Lebowski", "sport": "Bowling"}
</code>```

Body:
https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_2_1_2

You are exactly right in your understanding about representations, AND the RESTful way for you to get those different representation of one same is by doing content negotiation, using a standardised media type between the client and the server.

In HTTP, the standard way to do representation/content negotiation is by using the ACCEPT header (RFC 7231#section-5.3.2), with the standardised media ranges (RFC 6838#section-4.2).

I do think media type schemas, using the facets "." and suffix "+" part of the media type naming scheme should allowed and encouraged. That extension you did, IMHO it's also the right and pragmatic way to do it.

RAML does support multiple representations:

#%RAML 0.8
title: REST Content Negotiation Example
version: 0.1
baseUri: http://example.com

/v1/users/:
  displayName: users
  /{id}:
    displayName: id
    uriParameters:
      id:
        type: integer
    get:
      responses:
        200:
          body:
            application/vnd.myapp.v1+json:
              example: |
                {"id": 1234, "name": "Jeffery Lebowski"}

            application/vnd.myapp.v1.extended+json:
              example: |
                {"id": 1234, "name": "Jeffery Lebowski", "sport": "Bowling"}


问:
Is it true that calling _exit() instead of exit() won't prevent static destructors from being called?
On comp.lang.c++.moderated@googlegroups.com, Greg Herlihy posted the following extern "C" function:

```<code>extern "C"
{
    int func()
    {
        wchar_t memoryName[256];
        wchar_t mutexName[256];
        wchar_t eventName[256];
        mbstowcs(memoryName, "MemoryName", 256);
        mbstowcs(mutexName, "MutexName", 256);
        mbstowcs(eventName, "EventName", 256);
        std::wstring memoryString(memoryName);
        std::wstring mutexString(mutexName);
        std::wstring eventString(eventName);
        CDataTransferServer *srv = new CDataTransferServer();
        srv->Initialize(1, CC_SAMPLETYPE_MPEG4,128,256,64);
        printf("Inside entry point tester 1\n");
        srv->AddUser(5, memoryString, mutexString, eventString);
        printf("Inside entry point tester 2\n");
        delete srv;
        printf("Exiting entry point tester 3\n");
    }
}
</code>```

which is a g++ entry point different than main(int argc, char*argv[]).

Greg Herlihy then wrote:

Calling _exit() (which presumably should be "_Exit()") - does not "prevent"
  C++ global objects from being destroyed. The destruction of a C++ program's
  global objects is not inevitable. Instead a C++ program is responsible for
  destroying its own global objects - and can do so in one of two ways: the
  program returns from main() or it calls exit(). So a C++ program that fails
  to exit main() and neglects to call exit() before it terminates - will not
  have destroyed its global objects by the time it ended.

I don't believe that follows from what is written in the standard.

As far as I can see, when I call exit(), the spec guarantees that:

Destructors for objects with automatic storage duration
will not be called.

Destructors for objects with with static storage duration
will be called, in reverse order of construction.

The worrying thing is that the standard doesn't say anything about
    exit() or _exit(), so I'm relying on implementation-dependent behavior.

Not so. The C++ Standard specifies that calling exit() destroys global
  objects[3.6.3/1] And _Exit() is part of the C99 Standard (and will
  presumably be incorporated into the next C++ Standard by reference).

Right, the C++ standard says what exit() does, but it doesn't say what
_exit() or _Exit() do. And the C standard certainly doesn't say
anything about C++ destructors.

I don't see any implementation-defined behavior here. Calling _Exit() is no
  more likely to destroy a C++ program's global objects than calling printf()
  - or calling any other function that is not exit().

_exit() and _Exit() are specified not to call any functions registered
atexit() or on_exit(). However, that's not useful for C++ because the
C++ spec doesn't say by what means the runtime takes care of calling
destructors of objects with static storage duration. A compliant
implementation could use a mechanism other than atexit() or on_exit()
to invoke static destructors.

In other words, the C++ spec does not say anything all about the
behavior of _exit() or _Exit(). Therefore, I cannot make any assumptions
about whether or not calling either function will cause destructors
of static objects to run or not.

Any comments are welcome.

答:
On Linux, _exit(2) is a system call (often exit_group(2) is actually called). So if you call that raw syscall nothing else happens except that the current process is ending
and _exit

terminates the calling process "immediately".

A system call is, from the user-mode point of view, an elementary machine instruction (SYSENTER) which switches to kernel mode. And the kernel won't return into your program (whose process ceases to exist) after an _exit or exit_group syscall. And this is independent of the programming language and runtime. So nothing else happens, no code is running after (or before) the _exit, so no destructors (or anything else) is run.

Of course, exit(3) is a standard C library function :

All functions registered with atexit(3) and on_exit(3) are called, in
  the reverse order of their registration.

All open stdio(3) streams are flushed and closed.  Files created by
   tmpfile(3) are removed.

And global destructors are also called. Actually, I guess that something calling them is  registered by some equivalent of at_exit in the _start routine of crt0.

Since your C standard library is generally free software on Linux, you could study the source code of  exit; for musl-libc its exit/exit.c source file is quite readable.

Read also the POSIX specification of exit.


问:
Refactoring a long method which is based on large number of switch cases
We are using Java as a backend development language.

One year back, we wrote a method which uses switch cases based on Enums values. Since we are continuously adding enum members and according adding cases in the method, the method has grown to very large extent. Currently, we have around 100 enum fields and corresponding number of switch cases.e.g.

```<code> class AClass{

   enum option{ o1, o2, o3...on}

   Value method(Option o){

      switch(o){
        case o1:
          value = deriveValue(p1,p2,p3);
        case o2:
          value = deriveValue(p2,p3,p4);
        .
        .
        .
        case on:
          value = deriveValue(p1,p2,p3);
      }
   }
 }
</code>```

Thus each time a business requirement comes, we add enum and corresponding switch case. Now the method has become too long and looks unmanageable, if we keep on adding the same logic in future.

To clean, we thought of replacing switch case with polymorphism by creating classes for the same, but again, we will end up creating n number of classes.

We are looking for small, simple and manageable solution.

-----------------  Update ---------------------

As suggested, to elaborate more, Enum values are fields names for which a client needs a value. Thus if a client need the value of a new field, we add the field in enum, and the corresponding definition of how to fetch value for the newly added field, by adding the corresponding switch case.

In the switch case, we have a common reusable method e.g. deriveValue() (Please refer to the example given) to which we pass parameters required for deriving the value for the newly added field.

答:
What are you trying to achieve? Are you having difficulty understanding and maintaining the code structure you have, or are you just trying to follow some abstract idea of "good practice" that says methods should be short?

It looks to me as if the solution you have is quite adequate for the requirements you've been given. If there really are hundreds of similar computations that can be performed by a single line of code, then creating hundreds of subclasses with a single small method each is not necessarily better than simply listing all those parallel rules in one place. (The trouble with long methods is that they will become repetitive, inconsistent, and therefore confusing. But for listing a lot of parallel cases that have to be handled, a long list is perfectly fine.)


答:
You may create a table. The first column will be the switch value and the other columns will be the arguments passed on the deriveValue method. For example

```<code>table OPTIONS
OPTION -  ARGUMENT1 -  ARGUMENT2 -  ARGUMENT3
o1          p1          p2          p3
o2          p2          p3          p4
on          p1          p2          p3
</code>```

You can then write one general function that uses the above table to produce the appropriate function call based on the option.

Title: Refactoring a long method which is based on large number of switch cases

Body:
We are using Java as a backend development language.

One year back, we wrote a method which uses switch cases based on Enums values. Since we are continuously adding enum members and according adding cases in the method, the method has grown to very large extent. Currently, we have around 100 enum fields and corresponding number of switch cases.e.g.

```<code> class AClass{

   enum option{ o1, o2, o3...on}

   Value method(Option o){

      switch(o){
        case o1:
          value = deriveValue(p1,p2,p3);
        case o2:
          value = deriveValue(p2,p3,p4);
        .
        .
        .
        case on:
          value = deriveValue(p1,p2,p3);
      }
   }
 }
</code>```

Thus each time a business requirement comes, we add enum and corresponding switch case. Now the method has become too long and looks unmanageable, if we keep on adding the same logic in future.

To clean, we thought of replacing switch case with polymorphism by creating classes for the same, but again, we will end up creating n number of classes.

We are looking for small, simple and manageable solution.

-----------------  Update ---------------------

As suggested, to elaborate more, Enum values are fields names for which a client needs a value. Thus if a client need the value of a new field, we add the field in enum, and the corresponding definition of how to fetch value for the newly added field, by adding the corresponding switch case.

In the switch case, we have a common reusable method e.g. deriveValue() (Please refer to the example given) to which we pass parameters required for deriving the value for the newly added field.

Body:
You may create a table. The first column will be the switch value and the other columns will be the arguments passed on the deriveValue method. For example

table OPTIONS
OPTION -  ARGUMENT1 -  ARGUMENT2 -  ARGUMENT3
o1          p1          p2          p3
o2          p2          p3          p4
on          p1          p2          p3

You can then write one general function that uses the above table to produce the appropriate function call based on the option.