问:
Communication between Multiple Presenters in MVP
I'm designing an application using the MVP pattern, but a few of the edge cases for the system rely on communication between multiple presenters.

View 1 calls Presenter 1 which does Operation A returning Result X.

View 2, View 3, and View 4 are all interested in Result X. They each have their respective presenters, and can each respectively do Operation A and get Result X.

Our application has a MainView and a MainPresenter which effectively just house the other views and presenters.

One of the solutions was to give the MainPresenter references of Presenter 1, Presenter 2, Presenter 3, and Presenter 4. And having the result of Operation A call the other presenters.

Another was to implement a Facade layer that holds references to other presenters and it facilitates the other calls.

How have you handled this situation?

答: In my experience, if a result is needed in multiple places in the user interface, this suggests to me that the method for calculating it is a universal business rule, and therefore that rule has no business being implemented in a single presenter: it should be part of the domain model, instead.  At that point, no communication between presenters is needed, other than that they all reference the same domain model.</p>


问:
Can objects constructed from the same class have unique method definitions?
I know this seems like a weird question, since the point of two or more objects sharing the same class is that their behavior is the same, i.e. their methods are identical.

However, I'm curious if there are any OOP languages that allow you to redefine the methods of objects in the same way that you can assign different values for their fields. The result would be objects constructed from the same class no longer exhibiting the exact same behavior.

If I'm not mistaken, you can do this JavaScript? Along with this question, I ask, why would someone want to do this?

答:
I believe that is the definition of a "Dynamic" language like ruby, groovy & Javascript (and Many Many others).  Dynamic refers (at least in part) to the ability to dynamically redifine how a class instance might behave on the fly.

It's not a great OO practice in general, but for many dynamic language programmers OO principles aren't their top priority.

It does simplify some tricky operations like Monkey-Patching where you might tweak a class instance to allow you to interact with a closed library in a way they didn't forsee.

ContentLicense: CC BY-SA 3.0


问:
Which of these is the better way to structure functions in JavaScript?
I am new to programming (self teaching Javascript so I am missing some of the basics). I'm not sure if this falls under a style or best-practice question.

When writing a function that will be used often, and that has many slightly varied output expectations, should an internal if-statement be run to determine the output, or should the function be broken down into specific functions.

eg. What is better (try to ignore the contents!)

1:

```<code>function changeColour(colour){
  this.removeColour();
  switch(colour){
    case "red":
      this.colour('red');
    break;
    case "blue":
     this.colour('blue');
   break;
 }
}
</code>```

or

2.

```<code>function makeRed()
function makeBlue().. etc
</code>```

答:
Usually, you want to have exactly one place where your actual code is executed, which is what your first example is. However, sometimes you want easier code to both read and write. In your case, you might want to do something of this sort:

function changeColour(colour) {
  this.removeColour();
  switch(colour){
    case "red":
      this.colour('red');
    break;
    case "blue":
     this.colour('blue');
   break;
 }
}
function makeRed() {
  changeColour("red");
}
function makeBlue() {
  changeColour("blue");
}
```

This way, makeRed() and makeBlue() both have guaranteed results and are easy to read and write. Additionally, if there's a bug in your code, you're likely to squash it by only looking into changeColour(colour), which saves time and helps make your code bug-free.

We use this same practice with languages like Java, which only allow a fixed number of parameters per method, in order to make several methods with different parameters that do the same thing. For more, see https://stackoverflow.com/a/2632401/3939277, which does a good job of outlining this practice.

Body:
Usually, you want to have exactly one place where your actual code is executed, which is what your first example is. However, sometimes you want easier code to both read and write. In your case, you might want to do something of this sort:

function changeColour(colour) {
  this.removeColour();
  switch(colour){
    case "red":
      this.colour('red');
    break;
    case "blue":
     this.colour('blue');
   break;
 }
}
function makeRed() {
  changeColour("red");
}
function makeBlue() {
  changeColour("blue");
}

This way, makeRed() and makeBlue() both have guaranteed results and are easy to read and write. Additionally, if there's a bug in your code, you're likely to squash it by only looking into changeColour(colour), which saves time and helps make your code bug-free.

We use this same practice with languages like Java, which only allow a fixed number of parameters per method, in order to make several methods with different parameters that do the same thing. For more, see https://stackoverflow.com/a/2632401/3939277, which does a good job of outlining this practice.


问:
Coding style issue: Should we have functions which take a parameter, modify it, and then RETURN that parameter?
I'm having a bit of a debate with my friend over whether these two practices are merely two sides of the same coin, or whether one is genuinely better.

We have a function which takes a parameter, fills out a member of it, and then returns it:

```<code>Item predictPrice(Item item)
</code>```

I believe that as it works on the same object that is passed in, there is no point going on to return the item. In fact, if anything, from the perspective of the caller, it confuses matters as you could expect it to return a new item which it doesn't.

He claims that it makes no difference, and it wouldn't even matter if it did create a new Item and return that. I strongly disagree, for the following reasons:

If you have multiple references to the item passes in (or pointers or whatever), it allocating a new object and returning it is of material importance as those references will be incorrect.

In non-memory managed languages, the function allocating a new instance claims ownership of the memory, and thus we would have to implement a cleanup method which is called at some point.

Allocating on the heap is potentially expensive, and therefore it is important to whether the called function does that.

Hence, I believe it to be very important to be able to see via a methods signature whether it modifies an object, or allocates a new one. As a result, I believe that as the function merely modifies the object passed in, the signature should be:

```<code>void predictPrice(Item item)
</code>```

In every codebase (admittedly C and C++ codebases, not Java which is the language we are working in) I have worked with, the above style has essentially been adhered to, and kept to by considerably more experienced programmers. He claims that as my sample size of codebases and colleagues is small out of all the possible codebases and colleagues, and thus my experience is no true indicator over whether one is superior.

So, any thoughts?

答:
Syntax is different between different languages, and it is meaningless to show a piece of code that is not specific to a language because it means completely different things in different languages.

In Java, Item is a reference type -- it is the type of pointers to objects that are instances of Item. In C++, this type is written as Item * (syntax for the same thing is different between languages). So Item predictPrice(Item item) in Java is equivalent to Item *predictPrice(Item *item) in C++. In both cases, it is a function (or method) that takes a pointer to an object, and returns a pointer to an object.

In C++, Item (without anything else) is an object type (assuming Item is the name of a class). A value of this type "is" an object, and Item predictPrice(Item item) declares a function which takes an object and returns an object. Since & is not used, it is passed and returned by value. That means the object is copied when passed, and copied when returned. There is no equivalent in Java because Java does not have object types.

So which is it? Many of the things you are asking in the question (e.g. "I believe that as it works on the same object that is passed in ...") depends on understanding exactly what is being passed and returned here.


问:
Should I pass in filenames to be opened, or open files?
Suppose I have a function that does things with a text file - for example reads from it and removes the word 'a'.  I could either pass it a filename and handle the opening/closing in the function, or I could pass it the opened file and expect that whoever calls it would deal with closing it.

The first way seems like a better way to guarantee no files are left open, but prevents me from using things like StringIO objects

The second way could be a little dangerous - no way of knowing if the file will be closed or not, but I would be able to use file-like objects

```<code>def ver_1(filename):
    with open(filename, 'r') as f:
        return do_stuff(f)

def ver_2(open_file):
    return do_stuff(open_file)

print ver_1('my_file.txt')

with open('my_file.txt', 'r') as f:
    print ver_2(f)
</code>```

Is one of these generally preferred?  Is it generally expected that a function will behave in one of these two ways?  Or should it just be well documented such that the programmer can use the function as appropriate?

答: If you pass the file name around instead of the file handle then there is no guarantee that the second file is the same file as the first one when it is opened; this can lead to correctness bugs and security holes.</p>


答:
The convention I've seen codebases adhere to is to prefer a style that is clear from the syntax. If the function changes value, prefer pass by pointer

```<code>void predictPrice(Item * const item);
</code>```

This style results in:

Calling it you see:

predictPrice(&my_item);

and you know it will be modified, by your adherence to style.

Otherwise prefer pass by const ref or value when you don't want the function to modify the instance.

Title: Coding style issue: Should we have functions which take a parameter, modify it, and then RETURN that parameter?

Body:
I'm having a bit of a debate with my friend over whether these two practices are merely two sides of the same coin, or whether one is genuinely better.

We have a function which takes a parameter, fills out a member of it, and then returns it:

```<code>Item predictPrice(Item item)
</code>```

I believe that as it works on the same object that is passed in, there is no point going on to return the item. In fact, if anything, from the perspective of the caller, it confuses matters as you could expect it to return a new item which it doesn't.

He claims that it makes no difference, and it wouldn't even matter if it did create a new Item and return that. I strongly disagree, for the following reasons:

If you have multiple references to the item passes in (or pointers or whatever), it allocating a new object and returning it is of material importance as those references will be incorrect.

In non-memory managed languages, the function allocating a new instance claims ownership of the memory, and thus we would have to implement a cleanup method which is called at some point.

Allocating on the heap is potentially expensive, and therefore it is important to whether the called function does that.

Hence, I believe it to be very important to be able to see via a methods signature whether it modifies an object, or allocates a new one. As a result, I believe that as the function merely modifies the object passed in, the signature should be:

```<code>void predictPrice(Item item)
</code>```

In every codebase (admittedly C and C++ codebases, not Java which is the language we are working in) I have worked with, the above style has essentially been adhered to, and kept to by considerably more experienced programmers. He claims that as my sample size of codebases and colleagues is small out of all the possible codebases and colleagues, and thus my experience is no true indicator over whether one is superior.

So, any thoughts?

Body:
The convention I've seen codebases adhere to is to prefer a style that is clear from the syntax. If the function changes value, prefer pass by pointer

void predictPrice(Item * const item);

This style results in:

Calling it you see:

predictPrice(&my_item);

and you know it will be modified, by your adherence to style.

Otherwise prefer pass by const ref or value when you don't want the function to modify the instance.


问:
How to find duplicate strings
I allow my user to create profiles, meaning they potentially could create some with duplicate names.  This can be problematic so I want to prevent them from doing so.  I coded up this first pass recursive-ish algorithm for detecting what number copy I should assign to the Name, however I'm almost certain there is a better way to write it, but my writers block has dropped the hammer down on me--in fact, I wasn't even sure how to word the question or Google something that might already exist.  Here is the code:

```<code>//Check to see if there is another profile with the same name
var exiProf = profiles.FirstOrDefault(p => p.Name == newProf.Name);
int counter = 1;
while (exiProf != null)
{
    // Only match with the last number surrounded with parens
    Regex exp = new Regex(@"\((\d)\)$");
    Match ma = exp.Match(exiProf.Name);
    if(ma.Success)
    {
        num = int.Parse(ma.Groups[1].Value);
        var numChar = (counter).ToString();
        var nextNumChar = ( ++counter).ToString();
        newProf.Name = newProf.Name.Replace(numChar, nextNumChar);

        //Loop to make sure new name doesn't already exist
        exiProf = profiles.FirstOrDefault(p => p.Name == newProf.Name);
    }
    else
    {
        newProf.Name += " (" + num + ")";

        //Loop to make sure new name doesn't already exist
        exiProf = profiles.FirstOrDefault(p => p.Name == newProf.Name);
    }
}

profiles.Add(newProf);
</code>```

Meaning, if I try to add "New", "New", "New", "New" in that order, "New (1)", "New (2)", "New (3)", "New (4)" is what shows up in my list.

Note: I have tagged algorithms in here because I am capable of turning pseudocode into C#.

答:
I would think this will do it:</p>

```<code>if (profiles.Any(p => p.Name == newProf.Name))
{
    string template = newProf.Name + " ({0})";
    int counter = 1;
    string candidate = String.Format(template, counter);

    while (profiles.Any(p => p.Name == candidate))
    {
        counter++;
        candidate = String.Format(template, counter);
    }

    newProf.Name = candidate;
}
</code>```

Title: How to find duplicate strings

Body:
I would think this will do it:

if (profiles.Any(p => p.Name == newProf.Name))
{
    string template = newProf.Name + " ({0})";
    int counter = 1;
    string candidate = String.Format(template, counter);

    while (profiles.Any(p => p.Name == candidate))
    {
        counter++;
        candidate = String.Format(template, counter);
    }

    newProf.Name = candidate;
}


问:
Is naming a class based on its implementation acceptable?
Is naming a class according to its implementation an acceptable practice?

e.g. SortedSet if the class is maintains a sorted list of unique items or TreeSet if it using a binary search tree structure instead.

答:
Look no further than C++'s STL:

```<code>std::map
</code>```

std::map is a sorted
  associative container that contains key-value pairs with unique keys.
  Keys are sorted by using the comparison function Compare. Search,
  removal, and insertion operations have logarithmic complexity. Maps
  are usually implemented as red-black trees.

```<code>std::unordered_map
</code>```

std::unordered map is an
  associative container that contains key-value pairs with unique keys.
  Search, insertion, and removal of elements have average constant-time
  complexity.

Internally, the elements are not sorted in any particular order, but
  organized into buckets. Which bucket an element is placed into depends
  entirely on the hash of its key. This allows fast access to individual
  elements, since once hash is computed, it refers to the exact bucket
  the element is placed into.

```<code>std::set
</code>```

std::set is an
  associative container that contains a sorted set of unique objects of
  type Key. Sorting is done using the key comparison function Compare.
  Search, removal, and insertion operations have logarithmic complexity.
  Sets are usually implemented as red-black trees.

```<code>std::unordered_set
</code>```

std::unordered_set
  is an associative container that contains set of unique objects of
  type Key. Search, insertion, and removal have average constant-time
  complexity.

Internally, the elements are not sorted in any particular order, but
  organized into buckets. Which bucket an element is placed into depends
  entirely on the hash of its value. This allows fast access to
  individual elements, since once a hash is computed, it refers to the
  exact bucket the element is placed into.

I believe these examples reasonably reflect your case. This is just a smattering. There are a number of other examples.

However, note @Deduplicator's comment below, and my response. The STL names reflect differences in the how the classes can and should be used, not their internal implementations. I'm not sure about your example. If there is no impact on how a consumer interacts with the class, then IMO implementation details should not be reflected in its name. A class's name should reflect its intended usage by consumers.

If there is a significant different in performance, such as might be the case in your example, depending on the type and volume of data being stored, then perhaps a name reflecting that might work better. "SortedSet" and "QuickSet", for example, such as we find with Quicksort - although that is simply a generic name for a particular algorithm, not the formal name of a class.

Body:
Look no further than C++'s STL:

std::map

std::map is a sorted
  associative container that contains key-value pairs with unique keys.
  Keys are sorted by using the comparison function Compare. Search,
  removal, and insertion operations have logarithmic complexity. Maps
  are usually implemented as red-black trees.

std::unordered_map

std::unordered map is an
  associative container that contains key-value pairs with unique keys.
  Search, insertion, and removal of elements have average constant-time
  complexity.

Internally, the elements are not sorted in any particular order, but
  organized into buckets. Which bucket an element is placed into depends
  entirely on the hash of its key. This allows fast access to individual
  elements, since once hash is computed, it refers to the exact bucket
  the element is placed into.

std::set

std::set is an
  associative container that contains a sorted set of unique objects of
  type Key. Sorting is done using the key comparison function Compare.
  Search, removal, and insertion operations have logarithmic complexity.
  Sets are usually implemented as red-black trees.

std::unordered_set

std::unordered_set
  is an associative container that contains set of unique objects of
  type Key. Search, insertion, and removal have average constant-time
  complexity.

Internally, the elements are not sorted in any particular order, but
  organized into buckets. Which bucket an element is placed into depends
  entirely on the hash of its value. This allows fast access to
  individual elements, since once a hash is computed, it refers to the
  exact bucket the element is placed into.

I believe these examples reasonably reflect your case. This is just a smattering. There are a number of other examples.

However, note @Deduplicator's comment below, and my response. The STL names reflect differences in the how the classes can and should be used, not their internal implementations. I'm not sure about your example. If there is no impact on how a consumer interacts with the class, then IMO implementation details should not be reflected in its name. A class's name should reflect its intended usage by consumers.

If there is a significant different in performance, such as might be the case in your example, depending on the type and volume of data being stored, then perhaps a name reflecting that might work better. "SortedSet" and "QuickSet", for example, such as we find with Quicksort - although that is simply a generic name for a particular algorithm, not the formal name of a class.


问:
Using foldr to append two lists together (Haskell)
I have been given the following question as part of a college assignment. Due to the module being very short, we are using only a subset of Haskell, without any of the syntactic sugar or idiomatic shortcuts....I must write:

append xs ys : The list formed by joining the lists xs and ys, in that order

```<code>append (5:8:3:[]) (4:7:[]) => 5:8:3:4:7:[]
</code>```

I understand the concept of how foldr works, but I am only starting off in Functional programming. I managed to write the following working solution (hidden for the benefit of others in my class...) :

 append = \xs -> \ys -> foldr (\x -> \y -> x:y) ys xs

However, I just can't for the life of me, explain what the hell is going on!?
I wrote it by just fiddling around in the interpreter, for example, the following line :

```<code>foldr (\x -> \y -> x:y) [] (2:3:4:[])
</code>```

which returned [2:3:4] , which led me to try,

```<code>foldr (\x -> \y -> x:y) (2:3:4:[]) (5:6:7:[])
</code>```

which returned [5,6,7,2,3,4]

so I worked it out from there. I came to the correct solution through guess work and a bit of luck...

I am working from the following definition of foldr:

```<code>foldr = \f -> \s -> \xs -> if null xs then
                              s
                           else
                              f (head xs) (foldr f s (tail xs) )
</code>```

Can someone baby step me through my correct solution? I can't seem to get it....I already have scoured the web, and also read a bunch of SE threads, such as How foldr works

答:
append :: [a] -> [a] -> [a]

append = flip(foldr (:))

I try to explain foldr:

When we use foldr (:) [1,2,3] [4,5,6] without the flip

we take the second argument which is [4,5,6] the last element of the argument
is 6, which we apply with the (:) to our first argument [1,2,3] which will then give us [6,1,2,3].

Next last element is 5, which we will do the same operation on, that gives us [5,6,1,2,3].

Lastly we end up with [4,5,6,1,2,3], which isn't the right order only if we swap position of arguments
[1,2,3] with [4,5,6]
this we do by using flip(foldr (:)), which will give us the right order of arguments

and results in [1,2,3,4,5,6]


问:
memory needed to store a function in javascript
I have been using sizeof.js to investigate the size of various objects in javascript. It appears from this that the size of a function is essentially zero bytes, regardless of how many instructions the function executes. Why is this so?

答:
In most languages, code and data are different things.  They occupy different parts of memory and don't interact with each other.

When you ask the code "how big is this" you are asking about "how big is the instantiated object".  When looking at this you through tools like sizeof.js, you are asking the question "how big is the object representing the function pointer".  And in this case, the object doesn't have any additional properties its size is negligible.

Asking how big something in a language like javascript which is often not compiled down too far becomes one of "how big is this parse tree", which doesn't have any real meaning at runtime... nor is it always accessible.

Some languages such as Lisp, where the data and code can mix a bit more freely (the code is data), such a question can be slightly more meaningful, though not really.  While I'm sure if I fought with it long enough (my lisp is a bit rusty and I never delved into that realm of lisp metaprogramming), I could  come up with:

(defun double (x) (* x 2))

(print (somefunc 'double))
```

such that it would print out a value of 2, or 4 depending on how you wanted to define that.  But it's not a meaningful number in most cases.

Nor is the "how big is that function?" question asked of a javascript function pointer.  It is.  And whats more, under different javascript engines, if you could get a number, it would likely be different.

So:

The question you are asking of sizeof.js is giving you back the right number.

The object that represents the function pointer has no appreciable size associated with it.

Hypothetically, it could have data that wasn't the code associated with it and you would get back a different number.

The code lives in a different spot in memory than the data that sizeof.js may not have a way to access.

The size of the code isn't a meaningful number within the runtime.

Body:
In most languages, code and data are different things.  They occupy different parts of memory and don't interact with each other.

When you ask the code "how big is this" you are asking about "how big is the instantiated object".  When looking at this you through tools like sizeof.js, you are asking the question "how big is the object representing the function pointer".  And in this case, the object doesn't have any additional properties its size is negligible.

Asking how big something in a language like javascript which is often not compiled down too far becomes one of "how big is this parse tree", which doesn't have any real meaning at runtime... nor is it always accessible.

Some languages such as Lisp, where the data and code can mix a bit more freely (the code is data), such a question can be slightly more meaningful, though not really.  While I'm sure if I fought with it long enough (my lisp is a bit rusty and I never delved into that realm of lisp metaprogramming), I could  come up with:

(defun double (x) (* x 2))

(print (somefunc 'double))

such that it would print out a value of 2, or 4 depending on how you wanted to define that.  But it's not a meaningful number in most cases.

Nor is the "how big is that function?" question asked of a javascript function pointer.  It is.  And whats more, under different javascript engines, if you could get a number, it would likely be different.

So:

The question you are asking of sizeof.js is giving you back the right number.

The object that represents the function pointer has no appreciable size associated with it.

Hypothetically, it could have data that wasn't the code associated with it and you would get back a different number.

The code lives in a different spot in memory than the data that sizeof.js may not have a way to access.

The size of the code isn't a meaningful number within the runtime.


答:
sizeof.js is just giving you a ballpark estimation, not a definitive measure of how many bytes are actually used.  The actual amount of memory used is going to be implementation.  See this comment at the top of the sizeof.js source:

```<code>/* Returns the approximate memory usage, in bytes, of the specified object.
</code>```

Look at the source.  All it is doing is using a simple heuristic.  It assumes bools are four bytes, numbers are eight bytes and strings are two bytes per character.  Any or all of these could be wrong.  (Especially the string size estimation as it's clearly assuming no interesting Unicode.)  If it gets an object, it just treats its as a tree, adding up the sizes noted above non-object members and then adding the size of child objects in the same way.

This is decent enough if you want an estimate.  What it is not giving you is all the overhead used to store this stuff.  You aren't seeing the space used by all these references to objects, for instance.

In JavaScript, a function is just an object, and usually it is an object with no associated data members or child objects. So sizeof.js estimates its size as zero.  This does not mean no physical RAM is being used by it.  It almost certainly is, just like all the other overhead that's being missed, like the actual pointers in object references.

TL;DR - This is not like C sizeof, designed into the language with a contract to tell you exactly how many bytes to use (well, sorta.)  It's a back-of-the-envelope estimate that's good for only comparing structures and getting a rough idea of scope.

Title: memory needed to store a function in javascript

Body: I have been using sizeof.js to investigate the size of various objects in javascript. It appears from this that the size of a function is essentially zero bytes, regardless of how many instructions the function executes. Why is this so?

Body:
sizeof.js is just giving you a ballpark estimation, not a definitive measure of how many bytes are actually used.  The actual amount of memory used is going to be implementation.  See this comment at the top of the sizeof.js source:

/* Returns the approximate memory usage, in bytes, of the specified object.

Look at the source.  All it is doing is using a simple heuristic.  It assumes bools are four bytes, numbers are eight bytes and strings are two bytes per character.  Any or all of these could be wrong.  (Especially the string size estimation as it's clearly assuming no interesting Unicode.)  If it gets an object, it just treats its as a tree, adding up the sizes noted above non-object members and then adding the size of child objects in the same way.

This is decent enough if you want an estimate.  What it is not giving you is all the overhead used to store this stuff.  You aren't seeing the space used by all these references to objects, for instance.

In JavaScript, a function is just an object, and usually it is an object with no associated data members or child objects. So sizeof.js estimates its size as zero.  This does not mean no physical RAM is being used by it.  It almost certainly is, just like all the other overhead that's being missed, like the actual pointers in object references.

TL;DR - This is not like C sizeof, designed into the language with a contract to tell you exactly how many bytes to use (well, sorta.)  It's a back-of-the-envelope estimate that's good for only comparing structures and getting a rough idea of scope.


问:
Should access logic go in controllers?
I want to know if all the logic related to permissions and access control belongs to controllers (Application logic) or models (Business logic).

Currently I have a controller that does something like that:

```<code>function delete (resource) {
   if (resource.belongsTo (currentUser) {
       resource.delete ();
   }
   else {
       throw Exception ("you can't do this");
   }
}
</code>```

Is this kind of logic application logic or business logic?

PS. I already read Where to put business logic in MVC design?, but I still have doubts

答:
It is perfectly acceptable to put security/permissions logic in the controller method.

The purpose of the controller method is to coordinate service calls to the service layer or business logic layer or repository.  Technically, security is an orthogonal, but very important concern to the business logic methods.  It is orthogonal because it essentially boils down to a "gate" that you must pass through: either the resulting business logic method gets executed, or it does not.  But the essential logic itself does not change: assuming you have permissions, the outcome will always be the same.

The permissions function may be provided by another library or service, but that further underscores the role of the controller method as a coordinator, since now the controller method won't even be providing security functionality (it defers that functionality to some other mechanism).

Title: Should access logic go in controllers?


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

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

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

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

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

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

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

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

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

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

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

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

答:
There's Good Clever and Bad Clever.

Good Clever -- high ratio between clever lines of code vs lines of in a non-clever alternative. 20 lines of code that saves you from writing 20000 is Extremely Good Clever. Good Clever is about saving yourself work.

Bad Clever -- low ratio between lines of code written written vs. lines of code saved. One line of clever code that saves you from writing five lines of code is Bad Clever. Bad clever is about "syntactic masturbation".

Just to note: Bad Clever is almost never called "Bad Clever"; it will often travel under the aliases "beautiful", "elegant", "concise", or "succinct."

ContentLicense: CC BY-SA 2.5

Title: What's so bad about creative coding?


问:
Do we really need auto-vectorization?
I am trying to understand automatic parallelization and a special case of that is auto vectorization. As I understand it auto-vectorization is more or less:

The compiler takes parts of the code which are "serial" and transforms them to a vector.
For example:

```<code>X1=Y1+Z1
X2=Y2+Z2
Xn=Yn+Zn
</code>```

is transformed to

```<code>for(int i=0;i<n;i++)
X[i]=Y[i]+Z[i]
</code>```

Now we all know that the slowest part of code execution is branches. And if N is really really big then our code would really slow down in this case. So the compiler in this case would unroll our loop to something more like

```<code>for(int i=0;i<n;i+=4)
X[i]=Y[i]+Z[i]
X[i+1]=Y[i+1]+Z[i+1]
X[i+2]=Y[i+2]+Z[i+2]
X[i+3]=Y[i+3]+Z[i+3]
</code>```

So my question is why would the compiler vectorize my code if in so many cases of actions performed within loop on arrays are unrolled to multiple actions? Isn't it counter productive to roll code in a loop inside arrays and then unroll that loop?

答:
I think you are missing the most important step.  After the compiler turns your multiple statements into a loop, it then uses vector instructions such as SSE instructions to do multiple iterations of the loop in parallel.  If your hardware doesn't have vector instructions, then there would be no point.  So instead of unrolling the loop like you showed, it would be more like this:

```<code>for (i=0;i<n;i+=8)
    __vector_add8(&x[i], &y[i], &z[i]);
</code>```

Where __vector_add8 compiles to a vector instruction on your hardware that does 8 adds in parallel.

ContentLicense: CC BY-SA 4.0

Title: Do we really need auto-vectorization?

Body:
I think you are missing the most important step.  After the compiler turns your multiple statements into a loop, it then uses vector instructions such as SSE instructions to do multiple iterations of the loop in parallel.  If your hardware doesn't have vector instructions, then there would be no point.  So instead of unrolling the loop like you showed, it would be more like this:

for (i=0;i<n;i+=8)
    __vector_add8(&x[i], &y[i], &z[i]);

Where __vector_add8 compiles to a vector instruction on your hardware that does 8 adds in parallel.


答:
Auto vectorization doesn't actually work quite the way you think it does.   It does not turn your initial set of instructions into a loop: see, for example, the results of GCC compiling your code.

In general, auto-vectorization takes an unrolled loop, and transforms it so that the multiple statements you show in your example of an unrolled loop are implemented using a single assembly-language level instruction.

Title: Do we really need auto-vectorization?

Body:
I am trying to understand automatic parallelization and a special case of that is auto vectorization. As I understand it auto-vectorization is more or less:

The compiler takes parts of the code which are "serial" and transforms them to a vector.
For example:

```<code>X1=Y1+Z1
X2=Y2+Z2
Xn=Yn+Zn
</code>```

is transformed to

```<code>for(int i=0;i<n;i++)
X[i]=Y[i]+Z[i]
</code>```

Now we all know that the slowest part of code execution is branches. And if N is really really big then our code would really slow down in this case. So the compiler in this case would unroll our loop to something more like

```<code>for(int i=0;i<n;i+=4)
X[i]=Y[i]+Z[i]
X[i+1]=Y[i+1]+Z[i+1]
X[i+2]=Y[i+2]+Z[i+2]
X[i+3]=Y[i+3]+Z[i+3]
</code>```

So my question is why would the compiler vectorize my code if in so many cases of actions performed within loop on arrays are unrolled to multiple actions? Isn't it counter productive to roll code in a loop inside arrays and then unroll that loop?

Body:
Auto vectorization doesn't actually work quite the way you think it does.   It does not turn your initial set of instructions into a loop: see, for example, the results of <a href="http://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22JYOwLgBGCmDOkApSQB4EYA0FkRQJixxQGZDxcAWM1AVmtwDZ6UB2ZgDgwCgJtyBPTH0j8CwiP1Lj%2BVaXWlNpbaewCUXAN48I29BAC8uNBADUEtAG5deA7htnRV3iVsuHxJ5VcVTEip5QaVyCHGgCGVwiHBgCWVziHFgD2VxSHdk9tACdoMABXLJAjX3wS4hKfM0CSqNwE3AyuAF8gAA%3D%22%2C%22compiler%22%3A%22%2Fopt%2Fgcc-4.9.0%2Fbin%2Fg%2B%2B%22%2C%22options%22%3A%22-O3%20-msse2%20-ftree-slp-vectorize%22%7D%5D%7D" rel="noreferrer">GCC compiling your code.

In general, auto-vectorization takes an unrolled loop, and transforms it so that the multiple statements you show in your example of an unrolled loop are implemented using a single assembly-language level instruction.


问:
Combine union with distinct
Situation: I need distinct results from two tables, that both have duplicates.
I would like to know if I should combine UNION and DISTINCT.

Example 1 - Only use distinct

```<code>SELECT DistinctValue
FROM Table1
UNION
SELECT DistinctValue
FROM Table2
</code>```

Example 2 - Combine distinct and union

```<code>SELECT DISTINCT DistinctValue
FROM Table1
UNION
SELECT DISTINCT DistinctValue
FROM Table2
</code>```

The results are the same, but are there any performance differences?

答:
UNION in and of itself will deliver DISTINCT results.

UNION ALL is faster than UNION, but it does not remove duplicates.

Including DISTINCT in a UNION query does not add anything.

Title: Combine union with distinct


问:
Is there an accepted design pattern for storing a few global variables in a NoSQL database?
I'm wanting to create an admin dashboard for my app, and to show new events there. In order to know which events are new, I'll need to store at least one extra datapoint to the server: the last date at which the admin user (me) looked at the events and marked them all as read.

I'm trying to figure out where it makes sense to store that data.

I'm using Mongoose, and have a few different document types. Options I've considered include:

create an extra field on the user schema, that will be undefined for all non-admin users

create a new document type just to store admin data

use mongodb directly, rather than going through mongoose

Is one of these better than the others? Have I missed something that's obviously better than all of them?

答:
I have something similar in my app. If the admins are not too many, I have an array updatedUsers[] in each event document that contains the names of the people that have seen the event. If the user's name isn't in it then it's new for him. If you are going to query for new though, then you may need to reverse this (so you keep the notUpdatedUsers[] and query mongo for the username in this field, indexed of course).
mongoose or not is your choice.</p>


问:
Is there any mechanism to make programming language more stable(compatible) for changes?
There are a big number of programming languages. Some of them grow up and become very popular. People use such languages more and more often. The founder of such language (or founding organisation/community) may try to implement changes to make the language better. But sometimes it's hard to make some changes because of backward compatibility and such ugly things have already existed in the language for years, and are used by many users.

Are there any architectural principles or steps, during the language design phase, which can help to make it more stable so the language designers won't be as afraid to break backward compatibility?

答:
I think a pretty important step is to promote a package manager whicih can also manage the version of the language itself.

For instance, I use SBT for Scala or Leiningen for Clojure. Both of them let me declare which version of the language I want to use, per project. So it is quite easy to start green projects in the latest version of the language, while upgrading the existing projects at a more comfortable pace, if ever.

Of course, depending on the language, this may still leave you with the need to wait for the relevant libraries to be ported to the version you need (this happens, for instance, in Scala), but makes things easier nevertheless.


答:
Ask yourself this question: "if I do this, does it make the program easier to understand?".

Outside of functionality, one of your main goals when writing code should be clarity. Code is read many, many times more than it is written so it should be as easy to understand as possible. Choose patterns that aid in readability.

Title: Is naming a class based on its implementation acceptable?

Body:
Is naming a class according to its implementation an acceptable practice?

e.g. SortedSet if the class is maintains a sorted list of unique items or TreeSet if it using a binary search tree structure instead.


问:
Parameters Stored as Sessions - Pros / Cons?
Some background on my system:

I have 1 query with multiple pages. There are filtering parameters on the left of the page which $_POSTs on submission. The posted parameters will change the query at the top of the page.

My problem is that I am dealing with WordPress and the pagination is absolute links. Each time a user goes to a new page, I lose my $_POST array and the query resets.

I found a solution to this problem by storing my $_POST filtering parameters as $_SESSION parameters to bring them across multiple pages and thus keeping my query from resetting. Is this a bad idea?

I've read this question and answer: Results stored in a session - good idea? but I wasn't sure if it was the same situation as mine or differernt. In this question it seems he is storing entire database results into a session then cutting it up as he needs versus I'm still making database queries just using whatever was in the last session. I am also not using ajax to paginate as states above, I do lose my $_POST array.

Is this the same scenario as the question previous posted just a different flavor? Is use of $_SESSION acceptable?

答:
There are two major drawbacks to doing it this way:

Your site will break for any user who has cookies disabled. While this is not a common configuration, it does happen sometimes.

Users who try to open multiple tabs on your site may find their navigation going haywire.

I tend to avoid it for these reasons, but if it is the only realistic way (I've never worked with wordpress so don't know what alternatives you have) then neither of these is a complete showstopper.


问:
What would you consider best practice workflow tools for web application (PHP) development?
I'm really hoping somebody with more experience can edit the question as per my examples of answers:

using version control

test driven development

debugging code (xdebug for php)

use of UML diagrams

use of OOP for maintainable, reusable code

use of frameworks (like Zend Framework for php) for rapid application development

Anything else or an elaboration of what I mentioned above?

Basically, I'm in the middle of forming a team of developers (I'm a developer myself) and I'd like some advice on how professional programmers/designers etc should work together and what standards/paradigms they should use.

Also, if anybody has any books or links on the subject I'd welcome that!

I did find this which I guess satisfies what I'm looking for, or at least part thereof:

http://www.ibm.com/developerworks/websphere/library/techarticles/0306_perks/perks2.html

答:
Version Control: If on windows, TortoiseSVN is the best, most intuitive and easiest to use in my experience.

Framework: CodeIgniter. Hands on the best web development platform for PHP.

IDE: Netbeans is the best IDE for PHP that I've used on windows.

Unit Testing: There are several options, a google search will turn up many. CodeIgniter also has its own unit tester available.

Debugger: Xdebug.

Javascript Library: Jquery

FTP Program: FileZilla

Database Administration: PhpMyAdmin

Wireframing: Balsimus Mockup, or use a whiteboard.

Misc: Use WAMP if on windows to easily install, start, stop, & restart apache, mysql, and php all in one package.

Also, if you are going to be a working on many different websites, and most of those websites will have some common functions like signup, login/logout, an admin section for searching users, etc, I recommend building a small project in whichever framework you choose, and using that project as the base for every new project that you start. Normally I call this project 'skeleton'. If I'm going to start working on xyz.com, I would copy skeleton directory and rename it as 'xyz.com', fill in some configuration files, and I'd have a copy of xyz.com with some of the features already working.


答: Other answers have shown how this is a common feature of dynamic object-oriented languages, and how it can be emulated trivially in a static language that has first-class function objects (e.g. delegates in c#, objects that override operator () in c++). In static languages that lack such a function it is harder, but can still be achieved by using a combination of the Strategy pattern and a method that simply delegates its implementation to the strategy. This is in effect the same thing you'd be doing in c# with delegates, but the syntax is a bit messier.</p>

Title: Can objects constructed from the same class have unique method definitions?

Body:
I know this seems like a weird question, since the point of two or more objects sharing the same class is that their behavior is the same, i.e. their methods are identical.

However, I'm curious if there are any OOP languages that allow you to redefine the methods of objects in the same way that you can assign different values for their fields. The result would be objects constructed from the same class no longer exhibiting the exact same behavior.

If I'm not mistaken, you can do this JavaScript? Along with this question, I ask, why would someone want to do this?


答:
I have 1 query with multiple pages. There are filtering parameters on the left of the page which $_POSTs on submission.

That is your problem right there. A query should be a GET according to the HTTP verbs, and using a GET would make it easily possible to simply pass the search query along from page to page (this is how every single search engine does it).

Title: Parameters Stored as Sessions - Pros / Cons?

Body:
Some background on my system:

I have 1 query with multiple pages. There are filtering parameters on the left of the page which $_POSTs on submission. The posted parameters will change the query at the top of the page.

My problem is that I am dealing with WordPress and the pagination is absolute links. Each time a user goes to a new page, I lose my $_POST array and the query resets.

I found a solution to this problem by storing my $_POST filtering parameters as $_SESSION parameters to bring them across multiple pages and thus keeping my query from resetting. Is this a bad idea?

I've read this question and answer: Results stored in a session - good idea? but I wasn't sure if it was the same situation as mine or differernt. In this question it seems he is storing entire database results into a session then cutting it up as he needs versus I'm still making database queries just using whatever was in the last session. I am also not using ajax to paginate as states above, I do lose my $_POST array.

Is this the same scenario as the question previous posted just a different flavor? Is use of $_SESSION acceptable?


问:
Socket Connecting to Large number of IPs
I have a text file of ~600 CIDR notation IP blocks which, when expanded, amount to ~17.5M IP addresses. I need to socket connect to each one. If it connects, I add it to a "live" list, if it returns an error/refusal, to a "dead" list. Then the socket is closed. I don't need to read from it, I don't need to write to it. Obviously, this is a problem of scale, if we generously assume that the connection takes only one second to return success or failure, it would take months to complete, but likely several years. I need to get it down to <24 hours.

Right now I'm using Python to expand/count each of the IP addresses, because it is trivial to do so. I am writing a simple multi-threaded C program to address the above problem. There are a few ways I have thought of to tackle this:

Purely using C: I have not found a way to expand a CIDR block in C, (handling strings in general is a pain). I could probably cook something up, but if something already exists I'd love to hear about it.
Will I be able to spawn enough threads? Even if I spawn a thread for each block, that 600 threads! I feel like I need to shrink the stack space allotted to the threads to do this maybe? Even so, I need to be able to handle a large number of strings because the blocks need to be expanded. Regardless, I have looked at the list by hand, and one of the blocks has a /10 CIDR notation, which amounts to >4M IPs by itself. This would still take far too long.

Spawning C processes from Python: This would trivialize the string problem, and each individual IP could be sent to an instance of a C function called from Python, which would then end. The question I have is: when Python calls an external C function, does it continue running with the C process in parallel? Or does it wait for the C function to complete? I know Python does not allow multi-threading (or rather, it does, but it's somewhat of a joke since only one line is interpreted at a time), so is this the correct way to "export" multi-threading?

Vice versa: As above, but with C calling Python code, is this "more" correct? Which is to say, can C initiate multiple Python processes and continue to do it's own thing?

Something completely different.

Any questions, suggestions, or concerns are welcome. Please point out anything I might be missing or incorrect assumptions I have made.

Thank you for your help.

答:
You're going to struggle to make this work as well as you're hoping. The precise figures vary depending on operating system, but if you try opening more than a few hundred sockets at a time on an ongoing basis you're going to start running out  of system resources pretty quickly. On windows desktop machines the limit is lower still (windows desktop prevents activities like this as part of am intentional plan to reduce the effectiveness of ddos attacks and worms).

I would suggest:

use a single-threaded process and non-blocking i/o (e.g. select in c, I don't know if python supports this)

distribute your task over a small cluster so that you only need 100 or so sockets on each machine. A cloud service (eg amazon ec2) may be your best option.

Also see https://stackoverflow.com/a/3923785/441899 which has hints on tuning a linux system to increase the number of parallel connection attempts you can make.


问:
At what granularity are events recorded in Event Sourcing?
I'm growing my understanding of event sourcing.  My understanding is that it provides a means of recording events as they happen so that given a common beginning state and an audit log of recorded events, the events can be replayed to achieve the same final state.

I know that sometimes events are triggered by other events.  When I consider a system as a whole, I imagine that some events will be triggered externally by inputs from the user or another external source and that other events will be triggered and processed internally as side effects.  I am calling the former originating events and the latter secondary events.

Originating events trigger a domino effect of secondary events.  Since secondary events hinge directly on some originating event, should secondary events be recorded as part of the audit?

If you're aware of some source that discusses this in depth please cite.

答:
I think you're mixing up event sourcing and command sourcing. There is crucial difference between them. With command sourcing, you register external commands, like user inputs. In event sourcing, you register effects of those commands, i.e. what you've called secondary events.

In practice, you should choose either command or event sourcing and stick to it, not combining these 2 approaches. As for which one to choose, it seems that industry consensus is skewing towards event sourcing. For example, in Akka, the Akka Persistence module is based on event sourcing.

Main idea behind choosing event sourcing over command sourcing is that former allows for idempotency. I.e. however many times you replay the effects of your operation, your system would end up in the same state, while with command sourcing you're trying to rely on a fact that same command executed at different time would produce the same effect, which is, needless to say, is incautious.


问:
Race conditions in JVM languages versus C/C++
I was thinking about thread synchronization issues in compiled languages like C++, versus synchronization issues in languages like Java.

I'm wondering how a JVM language like Java doesn't (at least in practice) suffer from coredumps/segfaults/undefined behavior when race conditions occur.

Consider a C++ program with 2 threads.  Suppose each thread shares a reference to an std::vector<int>.  Each thread continuously loops, and calls std::vector<int>::push_back() - with no synchronization, no locking whatsoever.  In this scenario, it's very likely the program will segfault immediately, at least on any mainstream platform/compiler.  The reason is obvious: if one thread triggers a reallocation via a call to push_back, and the other thread ends up writing to the old, free'd memory buffer, your program is likely to core dump immediately.  Plus, the internal vector size and capacity values may get corrupted, leading to all sorts of undefined behavior and crashing.

But this doesn't seem to happen in Java.  Given the same scenario, where you have two threads, each with a reference to some unsynchronized data structure (like an ArrayList<Integer>), and each thread calls ArrayList<Integer>.add(), the worst that ever seems to happen in practice is an exception is thrown, probably an ArrayIndexOutofBounds exception - and of course, the order of insertion is totally random.

I realize the JVM is just executing byte code (except when it's executing JIT'd code), but ultimately that byte code or JIT machine code needs to interact with actual system memory.  I assume that Java automatically checks array indices with each access, and the language semantics and garbage collector ensure that all references are non-dangling - but with an unsynchronized data structure, when memory could literally be pulled out from under the program's feet by another thread, at any time, how is the JVM not segfaulting in this scenario unless it's somehow synchronizing memory reads/writes?

答:
In std::vector when a reallocation happens the old array is explicitly deleted, in java.util.ArrayList on the other hand, the old array is left to the garbage collection.

And the GC is conservative enough that the other thread's reference to the array will prevent it from being cleaned up.

but when memory could literally be pulled out from under the program's feet by another thread, at any time, how is Java not segfaulting in this scenario?

When any thread can still reference a block of memory it is not collected. In other words memory is never pulled out of any thread.


问:
in scala type linearization explain first step in algorithm
I saw this explanation

Where first step is:

"start building a list of types, the first element is the type we’re
  linearizing right now,"

however the result of this is:

```<code>// start with D1:
B with C with <D1>
</code>```

I don't get it.  We start with D1 why is it in <> at all? why is C with D1 and not D1 with B.  I don't get whats going on there, can you please explain?

答:
You will have to read the example a few times. I infer from the text elsewhere that the <> (diamonds) is a way to highlight the type we are looking at. So the type is

```<code><D1>
</code>```

D1 is defined as

```<code>class D1 extends B with C
</code>```

Since D1 is lowest in the hierarchy, it is shown last.

```<code>B with C with <D1>
</code>```

The rest of the steps are expansions of B and C, and the subsequent linearization.

Overall, I think the author's example, in this case, is confusing. He is using Scala syntactic form to show a semantic process. While this can work quite well for demonstrating, for instance, the substitution principle, here it confounds syntax and semantics, instead of clarifying them.

Body:
You will have to read the example a few times. I infer from the text elsewhere that the <> (diamonds) is a way to highlight the type we are looking at. So the type is

<D1>

D1 is defined as

class D1 extends B with C

Since D1 is lowest in the hierarchy, it is shown last.

B with C with <D1>

The rest of the steps are expansions of B and C, and the subsequent linearization.

Overall, I think the author's example, in this case, is confusing. He is using Scala syntactic form to show a semantic process. While this can work quite well for demonstrating, for instance, the substitution principle, here it confounds syntax and semantics, instead of clarifying them.


答:
It's a question of preference. Core dumps can only happen in a (properly implemented) language runtime if you invoke undefined behaviour, since they are never desired; and the designers of Java went to very great length to banish all undefined behaviour from the language.

The attitude of the C++ community tends to be "We need to make it possible to achieve anything anyone might want, for people who know what they are doing; but if someone makes a mistake, that's their problem". Java had many more years of hindsight, and the inventors decided that on the average, people are better served with a language that doesn't allow some things and makes other things somewhat slower than they would optimally be, for the sake of completely banishing runtime problems caused by undefined behaviour. This means checks before array accesses, pointer dereferencing, garbage collection etc., but on the whole the decision paid off, since computers got ever faster and cheaper, while programmers are just as expensive for an employer as they always were.

Title: Race conditions in JVM languages versus C/C++

Body:
I was thinking about thread synchronization issues in compiled languages like C++, versus synchronization issues in languages like Java.

I'm wondering how a JVM language like Java doesn't (at least in practice) suffer from coredumps/segfaults/undefined behavior when race conditions occur.

Consider a C++ program with 2 threads.  Suppose each thread shares a reference to an std::vector<int>.  Each thread continuously loops, and calls std::vector<int>::push_back() - with no synchronization, no locking whatsoever.  In this scenario, it's very likely the program will segfault immediately, at least on any mainstream platform/compiler.  The reason is obvious: if one thread triggers a reallocation via a call to push_back, and the other thread ends up writing to the old, free'd memory buffer, your program is likely to core dump immediately.  Plus, the internal vector size and capacity values may get corrupted, leading to all sorts of undefined behavior and crashing.

But this doesn't seem to happen in Java.  Given the same scenario, where you have two threads, each with a reference to some unsynchronized data structure (like an ArrayList<Integer>), and each thread calls ArrayList<Integer>.add(), the worst that ever seems to happen in practice is an exception is thrown, probably an ArrayIndexOutofBounds exception - and of course, the order of insertion is totally random.

I realize the JVM is just executing byte code (except when it's executing JIT'd code), but ultimately that byte code or JIT machine code needs to interact with actual system memory.  I assume that Java automatically checks array indices with each access, and the language semantics and garbage collector ensure that all references are non-dangling - but with an unsynchronized data structure, when memory could literally be pulled out from under the program's feet by another thread, at any time, how is the JVM not segfaulting in this scenario unless it's somehow synchronizing memory reads/writes?


答:
Consider the effects race conditions can have on actual hardware, not in the C++ undefined behavior theory.

On the high level, you get unpredictable insertion order, possibly lost insertions, or even corrupted data structures. You can totally get these in Java. (If you do racing insertions/removals on a LinkedList for long enough, eventually you'll probably have inconsistent next/prev links on the nodes leading to differing forward and backward traversal sequences.) They do not lead to crashes because they're high level behavior. But they will lead to various exceptions, or simply unexpected data.

On the mid level, you get pointers changed under your feet, indices that are out of date, etc. Java's semantics ensures that these are cleanly caught and converted to exceptions. Null pointers are always checked, indices are always checked, and the garbage collector makes dangling pointers impossible. (The garbage collector is implemented in a fully thread-safe way. No matter what race conditions the programmer writes, he cannot interfere with the garbage collector, because the synchronization there is not visible to the programmer.) These checks are written in a way that prevents race conditions to circumvent them: for example, arrays in Java cannot change in length, and they cannot be replaced or invalidated while you hold a reference (GC again), so if the compiler just creates a guaranteed-thread-local reference before checking the index, there can be no race condition between the index checking and the actual access.

On the low level, you get the really weird stuff: torn reads and writes, out-of-thin-air values, where completely invalid pointer values could appear: the kind of stuff that motivates C++ specifiers to say that any race condition corrupts the program now and forever, and even backwards in time. Java is implemented in a way that at least prevents this really weird stuff. Reads and writes of machine words are aligned, and if the architecture is flaky enough, probably implemented in a safer way than your typical C++ access, at the cost of some performance. By taking this precaution, Java can avoid crashes on the lowest level.

Finally, you have the compiler level, where the compiler will optimize your code under the assumption that race conditions do not happen. This is a nice source of weird errors in C++ even on very consistent architectures such as x64, and a good counterargument to those who claim that "this code is perfectly safe, I know how the CPU works". Java compilers simply don't perform such optimizations where they could lead to crashes. In particular, the special handling of array bounds checking I described above could be optimized away if you assume that race conditions do not happen. Repeated reads from the same pointer, if the pointer is shared but not synchronized, do not need repeated null checks, if you assume that race conditions do not happen. Java compilers do not make this assumption, and either repeatedly check for null, or create an unshared copy of the pointer, which turns the dangerous segfaulting race condition into a "harmless" (doesn't crash, just produces weird behavior) "why does my write have no effect?" race condition.

To sum up, Java does a few low-level things to prevent hard crashes at the cost of a little performance. High-level weird stuff can still happen, but will very often result in some kind of exception, and is usually easier to debug.


问:
Where does authorization fit in a layered architecture?
Typically, I place authorization decisions in my server side controllers.  These have been RESTful endpoints recently, but I think the same stands for MVC type architectures.  For the sake of argument assume that it's role based authorisation.  A protected method will be annotated or make checks and return 403s if necessary.

Now, given that authorisation is in fact a business rule - "only administrators can list X" for example, I'm thinking they should be pushed down a layer.  When a controller asks the business layer to perform the operation, the service or business layer informs the controller it's not authorised.

Is this a reasonable approach?  Are there disadvantages to this?

I'm loathe to have an AuthorisationService that essentially holds a bunch of static procedural coded rules to do this but maybe it makes sense to keep all access logic in one place. Is it a cross cutting concern that should be kept separate?

So I'm asking if anyone has done this and how they achieved it in a clean way or if there are any good resources I could read.  I'm using Java fwiw but this is a language agnostic question.

I've checked out the related questions on here and they're very thin on the ground and answers.  For example: Validation and Authorisation in Domain Models and Carrying that through a Service Layer to MVC

I'm reading the spring security docs which make some good arguments for it being a cross cutting concern, but I'm worried it's just the "spring way" and would like wider perspectives.  It also ties your application to a specific framework.

答:
I think it's absolutely reasonable approach to engrain authorization in your Service layer. You need to protect your service from performing unauthorized activities(especially data-modifications). Your Service layer could resides in one library, and being used by different Presentation layers(you could have different UI-applications, that use the same Service layer). And you can't rely on the fact that specific Presentation layers perform necessary validation. This is especially important if you will decide afterwards to move your Service layer to the separate process(e.g. following SOA approach).

Now about how to achieve this in a "clean way". I don't like the idea of littering business logic with authorization checks, so some specific implementation of aspect-oriented-programming-approach could help: it could be decorating service methods with special attributes or using dynamic proxies with interceptions.

And importantly, I need to admit that in very simple projects, may be, you could live without separated validations, just to simplify your life. But it's important do not miss the moment when "simple project" began to become "complex project".


答:
@ratch freak's answer is correct but the reason for the segfault is likely to be slightly different.

std::vector holds its values in place. In the case of std::vector<int> that just means that it contains an array of ints. For objects it means it uses inplace new.

So, on a re-allocation of the internal array, any extraneous reference to the original array or the data in it will point to free'd memory so is likely to crash.

In Java, an ArrayList will always hold references to Objects i.e. pointers. So even if the implementation copied its internal array, there is a good chance that the reference you hold will still be in the new array.

In other words, you could make the C++ segfault less often if you used std::vector<int *> . This isn't a recommendation btw. It's now not only a bad idea it's likely to be a slow, bad idea.

@ratchet freak's point is more subtle. Even though the ArrayList doesn't hold any references to its old internal array after the re-allocation, you may do, accidentally. In C++ this will probably barf. In Java, the GC knows you hold a reference, even if you didn't mean to, and won't free the array even though it now no longer belongs to the ArrayList. As a result the behaviour will be unpredictable but it probably won't segfault.


答:
The second option is way better.

Applying an ORM sort of architecture would be awesome.

The user's schema should probably have an extra field named account_type which will be mapped to account schema which contains list of all type of users on your application. Or you can have an extra string field called authorities, so for a normal user will have the ROLE_USER and probably ROLE_ADMIN for the admin user.

A different schema should hold your event data with an extra field in it named status which could hold the value "READ" or "UNREAD" depending on which works for you.

Title: Is there an accepted design pattern for storing a few global variables in a NoSQL database?

Body:
I'm wanting to create an admin dashboard for my app, and to show new events there. In order to know which events are new, I'll need to store at least one extra datapoint to the server: the last date at which the admin user (me) looked at the events and marked them all as read.

I'm trying to figure out where it makes sense to store that data.

I'm using Mongoose, and have a few different document types. Options I've considered include:

create an extra field on the user schema, that will be undefined for all non-admin users

create a new document type just to store admin data

use mongodb directly, rather than going through mongoose

Is one of these better than the others? Have I missed something that's obviously better than all of them?


问:
How to introduce Agile to a team that uses rigid non-Agile methods?
Consider a company that is proudly certified for some non-Agile methodology, uses it as a selling point to its customers to demonstrate accountability.

How do you go about introducing Kanban or Scrum progressively without breaking their whole system and still making them confident that it can still be just as accountable / auditable?

I know this is possibly related to "How would you introduce an agile methodology like Scrum", but here I am wondering about ways to circumvent/work around the fact that the company imposes a certain way of managing the SDLC under the false pretense that it's the only way to have an audit trail.

答:
I think it's a myth that Agile project teams don't document their applications and this is the first point of resistance you get in companies that are certified to have the best documentation as per their standards.

I work in an ISO-9001 certified company, but we ALSO do Scrums on a large number of our projects. In our case, the change came in from the Project Delivery heads (i.e. quite senior folks) and that's why it gets adopted - as opposed to a Project Manager or Developer trying to push in this change.

One useful practice we follow is Document Enough but Continuously . This obviously means we do not follow all the templates prescribed for the project, but there is a conscious understanding and agreement over which sections/documents are needed vs those that are just pointless overheads.

You'd then need to socialize this point of view and get the approval of the Quality group or Standards division or whatever it's called.

The Agile principle is 'just enough' documentation. Can you try and push it from the Customer to express to the team how much is just enough? The project manager could talk to the customer and understand what their expectations and organizational needs are and then both document the decision and meet those expectations. If it's good enough for them (i.e. the paying customers), then it can be what you follow.

If they think Agile doesn't scale up to large projects, convince them it can - by decomposition and parallel effort.

In large organization, control and oversight for large programs are accomplished by running a Project Monitoring Offices (PMOs) that conduct conventional planning for costing/accounting/resource management etc - hence they demand a lot of documentation, but they can monitor progress using Agile practices (the SCRUM burn-down chart for one). They need to know how techniques such as continuous integration help them earlier rather than later, and hence it's better for everyone's productivity to get overhead docs out of the way.

Agile is a set of skills that a team can learn which is largely orthogonal to our traditional technical skills. But if you add this to their existing skills, of course you can become a more effective team. Daily standups (i.e. Scrum meetings) are not going to be possible overnight - but you would have regular team meetings (say bi-weekly) at present? I'd say start by converting those into following the Scrum question agenda (not too sneakily ;) and convey to the wider team why this approach can work and does not mean lax documentation / poor standards or whatever other myths.


答: absolutely awesome practice.  also try having some sort of base controller that have all other of your controller extended to it to avoid repetitive access control check. let's say i want to limit people from visiting the profile controller, i can have a parent controller called user and right in the constructor i would do a check to see if user has access else i will redirect. if you decide developing with java, you should probably try the spring security (http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html) which is awesome and eliminates much need for the struggle for access controls from the controllers.</p>

Title: Should access logic go in controllers?

Body:
I want to know if all the logic related to permissions and access control belongs to controllers (Application logic) or models (Business logic).

Currently I have a controller that does something like that:

```<code>function delete (resource) {
   if (resource.belongsTo (currentUser) {
       resource.delete ();
   }
   else {
       throw Exception ("you can't do this");
   }
}
</code>```

Is this kind of logic application logic or business logic?

PS. I already read Where to put business logic in MVC design?, but I still have doubts


答:
Java implements the Java Memory Model which states what should happen in certain situations, and dumping core is not mentioned anywhere in this document. So any Java implementation must take care to implement what the memory model says, and thus throwing core is not permitted. It does sometimes happen, though rarely, but only as a result of bugs in the implementation.

How a particular implementation achieves adherence to the Memory Model rules is left to the implementor - it is only the final behavior which matters. Others have already mentioned that the Garbage Collector plays an important role here and that in particular as long as you have references to an object in any thread, that object can not be freed from memory.


问:
Is the application architecture of Facebook Flux a new idea?
Facebook announced that it's using the architecture they call Flux to develop their projects.

It consists of a single direction dataflow, and concepts like a Dispatcher, Stores and Actions (well described here).

This is their illustration of how the pieces glue together:

```<code>Views ---> (actions) ----> Dispatcher ---> (registered callback) ---> Stores -------+
Ʌ                                                                                |
|                                                                                V
+-- (Controller-Views "change" event handlers) ---- (Stores emit "change" events) --+
</code>```

My question is: Is that a new idea? Is it a application architecture used before? Is it a "best practice" borrowed from another language/framework?

The purpose of this question is to deepen the knowledge about the architecure which have been gaining lots of attention lately, and seem very different from the MV* pattern most developers I know have been working with.

答:
I don't recall seeing the specific Views -> Dispatcher -> Stores architecture before, but the more general concept of a "flow" has been around a while, as they mention in the article you linked:

This structure allows us to reason easily about our application in a way that is reminiscent of functional reactive programming, or more specifically data-flow programming or flow-based programming, where data flows through the application in a single direction — there are no two-way bindings.

There's a ton of information and some existing implementations out there if you search those terms.  I've done some functional reactive programming with elm.  The restrictions it forces on you are sometimes difficult to work within, but those restrictions also make it very difficult to get into an inconsistent state or create weird update cycles.


问:
Obsessed with filling hashmaps instead of using else if cascades or switch statements
Whenever I feel like choosing from a list of implementations I always prefer to fill a map first and then call whatever I need based on a parameter, instead of using switch or else if statements.

What is the pattern I'm looking for here? I've been told repeatedly that using maps is not the optimal solution for this, but I find writing those statements a bore.

I tagged the languages I'm currently working with, but this is not a language specific question.

答:
As amon pointed out in his comment, that's called a dispatch table.  It's one way to implement the more general concept of ad hoc polymorphism.

Since nearly every language after C supports ad hoc polymorphism natively in one form or another, it's unlikely that your solution is either more readable or more efficient, except in limited circumstances like deserialization.  Even then, more expressive languages have constructs that can help you there, like clojure's multimethods.

Find out how your language does ad hoc polymorphism.  It's the right solution for 99% of situations where you need to choose between different implementations.


问:
Why is the Unix linker called "ld"
Tried to search the web and couldn't find an answer. It might have something to do with "load", but that doesn't make much sense to me.

Obviously, "ln" was already taken, but where does that "d" come from?

答:
Because it is "link editor". For example, Solaris and AIX man pages explicitly say so:

Solaris ld man page

ld - link-editor for object files

AIX ld man page

The ld command, also called the linkage editor or binder

In the comment to the question there is an extremely interesting link to 1971 UNIX man pages. There is a ld man page, which explicitly states ld - link editor, see the man12.pdf file (page 20):

NAME ld -- link editor

Wikipedia mentions that there are different theories, one is "loader" one is "link editor".

Sidenote - amazing, regular expressions already existed in 1971...

Title: Why is the Unix linker called "ld"


问:
Should we add constructors to structs?
We often use c++ structs to define data structure as opposed to class which can be a complete module with member methods. Now deep down, we know they both are the same (loosely speaking).

The fact that we often use/treat structs as data only entities creates this urge that we not add default constructors as well. But constructors are always great, they make things simpler and help eliminate errors.

Would it be frown upon if add default constructors to my data structures?

Does implementing default constructor also make the struct Non-POD (plain old data type) provided other criteria are met?

To put things in perspective, consider a simple example but in reality the struct would be much larger.

```<code>struct method
{
    char    name[32];
    float   temperature;
    int     duration;
};
</code>```

Every time I create a method, I have to worry about (to say the least) if I forgot to set some value. Imagine I forget to set temperature and apply the method to system which is now a random high value and causes mayhem. Or I forgot to set duration and now the method applies itself for an unknown high duration.

Why should I take responsibility to initialize the object every time instead of implementing its constructor which guarantees it?

答:
Sometimes it's appropriate to add constructor to a struct and sometimes it is not.

Adding constructor (any constructor) to a struct prevents using aggregate initializer on it. So if you add a default constructor, you'll also have to define non-default constructor initializing the values. But if you want to ensure that you always initialize all members, it is appropriate.

Adding constructor (any constructor, again) makes it non-POD, but in C++11 most of the rules that previously applied to POD only were changed to apply to standard layout objects and adding constructors don't break that. So the aggregate initializer is basically the only thing you lose. But it is also often a big loss.

Title: Should we add constructors to structs?


问:
How can I convince management to deal with technical debt?
This is a question that I often ask myself when working with developers. I've worked at four companies so far and I've become aware of a lack of attention to keeping code clean and dealing with technical debt that hinders future progress in a software app. For example, the first company I worked for had written a database from scratch rather than use something like MySQL and that created hell for the team when refactoring or extending the application. I've always tried to be honest and clear with my manager when he discusses projections, but management doesn't seem interested in fixing what's already there and it's horrible to see the impact it has on team morale.

What are your thoughts on the best way to tackle this problem?
What I've seen is people packing up and leaving. The company then becomes a revolving door with developers coming in and out and making the code worse. How do you communicate this to management to get them interested in sorting out technical debt?

答:
For the life of me I can't understand why some people are so blindly afraid of change--it smacks of lacking confidence in your own abilities.

I watched a show last night on Yosemite National Park and it was remarked that from 1940 through the late 1990's not a single new Sequoia tree sprouted.  It was discovered that the reason why was that there was a strict policy against letting forest fires to burn and that Sequoia pine cones needed the heat from fire to open and release their seeds.

You see, a fire every ten years or so was healthy.  It cleared out all of the accumulated deadwood and bramble to keep healthy the existing trees (processes) and make room for new ones (features).

I am on a project right now that has a clear case for rebuild: The legacy software was written entirely using .NET webforms.  Almost all of the business logic is co-mingled with HTML/server tag view logic and can not be extended into other applications now that the business has grown.

Management is behind the task because they have an appropriate amount of trust in their developers which, I realize, is a rare luxury.

Yes, ask yourself if a rebuild is truly necessary.  Do your best to reuse existing code that works where you can.  Integrate that code into the rebuild if necessary.  Just don't let anyone convince you that being afraid of making bold changes is the only way to exist as a software developer.

Good luck!


答:
I'm not familiar with Mongoose but we have started pushing configuration out of xml files and into the DB using ravendb. Our approach is to:

We create a configuration object or object graph with sensible defaults.

We write a configuration manager class that provides:

automatic creation of the object if it does not exist

singleton access to the class

manages caching, etc if required

On the database level it is just a special document with a fixed ID -- hence the singleton. We have had a few approaches where we could swap various configurations into the "active" singleton as well. From the code's perspective little has changed -- we typically injected configuration using IoC containers so the codebase has been pretty agnostic. Config is just manna from heaven.

Overall I'm pretty happy with it. The biggest downside is it takes config out of version control which is a feature I've really liked for the auditability aspect.


问:
Native mobile app development - how do I structure my user stories?
I'm about to start on a project which will involve developing prototype native mobile apps (iOS and Android initially) as well as a web-based admin interface and an API for these apps to communicate with.  We've got a list of stories already drafted up, however a lot of them are in the format:

```<code>As a mobile user I want to be able to view a login screen so that I can sign into the app
</code>```

If this were targeted for a single platform, I wouldn't see a problem.  However, since we're targeting multiple platforms, I'm not sure whether these should now be duplicated eg "As an Android user" or similar.  This seems like duplication, but it's work that will need to be completed separately for each platform.

This is the first mobile project we've gone native on - previously it was Phonegap and we lumped all stories in under "As a mobile user".  Since essentially this was a web-based app wrapped in native code, this didn't present too much of an issue, but I'm conscious that wholly-native apps are a different ballgame!

答:
For anyone that has pulled up this page, maybe this response can help provide an option for successfully developing an app for both iOS/Android platforms.

As a project manager that has managed Agile/Scrum projects the explanation above of developing the same application for two different operating systems would indicate two separate workstreams.

To do this successfully would require two separate projects.  Each OS will have their own requirements.  By mixing the two OS's in a single project you could potentially create confusion on what is to be developed in either OS.  Thus, your team could lose valuable time deciphering which OS the requirement belonged.  In summary.

I would recommend setting up two projects with their own set of user stories that are specific to the OS.


答:
Quick Answer:

It depends on what do you want to achieve.

Long, Extended, Boring Answer:

You hit the nail.

I usually dislike that "C++" allows "Struct (s)" allows to declare methods. Preferably, I use explicit "Class (es)" for methods required and P.O.D. "Struct (s)" for only fields.

Yet, I agree that some basic simple operations, like:

assign initial values ("constructor")

make a copy of a structure ("copy constructor)

assign values to an existing structure ("overload assign operator")

Are required, and, in those circumstances, methods for structures, make sense.

Suggestion

Another potential solution is to use P.O.D. structures, but, still conceptually treat them as classes and objects.

Wrap those declarations in a namespace, and, add global functions, for the most important actions.

The code declaration could be similar to this:

```<code>namespace Customers
{
  struct CustomerStruct
  {
    char[255] FirstName;
    char[255] LastName;
    int Age;
    bool IsAlive;
    bool IsMarried;
  }; // struct

  CustomerStruct* CreateCustomer
  (
    char* NewFirstName;
    char* NewLastName;
    int NewAge;
    bool NewIsAlive;
    bool NewIsMarried;
  )
  {
    CustomerStruct* NewCustomer = new CustomerStruct();
      NewCustomer->FirstName = NewFirstName;
      NewCustomer->LastName = NewLastName;
      NewCustomer->Age = NewAge;
      NewCustomer->IsAlive = NewIsAlive;
      NewCustomer->IsMarried = NewIsMarried;
    return NewCustomer;
  } // CustomerStruct* CreateCustomer (...)

} // namespace
</code>```

The code that applies the solution, could be something like this:

```<code>#include <Customers>

using Customers;

int main (...)
{
   int ErrorCode = 0;

   CustomerClass* ThisCustomer =
     Customers::CreateCustomer
      ("John", "Doe", 23, true, true);

   // do something with "ThisCustomer"

   delete ThisCustomer;

   return ErrorCode;
} // int main(...)
</code>```

This alternative approach is better when a huge memory allocation of data is required, or interacting with other low-level shared libraries.

This approach, with some changes, is applied in Game Development.

Extra

Personally, I consider a syntax extension for "C++", or even, a new "C++" based P.L. that solves this issue:

```<code>// "Plain Old Data" Structure
// No Methods, No "Functors", allowed
strict struct CustomerStruct
{
  char[255] FirstName;
  char[255] LastName;
  int Age;
  bool IsAlive;
  bool IsMarried;
}; // strict struct

// Object Oriented "Plain Old Data" Structure
// Yes, Methods and "Functors" allowed
relaxed struct CustomerStruct
{
  char[255] FirstName;
  char[255] LastName;
  int Age;
  bool IsAlive;
  bool IsMarried;

  public void Foo();
  public void Bar();

  public (void*) (SomeFunctor) ();
}; // relaxed struct

// Class and Object Oriented
class CustomerClass
{
  public char[255] FirstName;
  public char[255] LastName;
  public int Age;
  public bool IsAlive;
  public bool IsMarried;

  public void Foo();
  public void Bar();
}; // class
</code>```

Cheers.

Title: Should we add constructors to structs?

Body:
We often use c++ structs to define data structure as opposed to class which can be a complete module with member methods. Now deep down, we know they both are the same (loosely speaking).

The fact that we often use/treat structs as data only entities creates this urge that we not add default constructors as well. But constructors are always great, they make things simpler and help eliminate errors.

Would it be frown upon if add default constructors to my data structures?

Does implementing default constructor also make the struct Non-POD (plain old data type) provided other criteria are met?

To put things in perspective, consider a simple example but in reality the struct would be much larger.

```<code>struct method
{
    char    name[32];
    float   temperature;
    int     duration;
};
</code>```

Every time I create a method, I have to worry about (to say the least) if I forgot to set some value. Imagine I forget to set temperature and apply the method to system which is now a random high value and causes mayhem. Or I forgot to set duration and now the method applies itself for an unknown high duration.

Why should I take responsibility to initialize the object every time instead of implementing its constructor which guarantees it?

Body:
Quick Answer:

It depends on what do you want to achieve.

Long, Extended, Boring Answer:

You hit the nail.

I usually dislike that "C++" allows "Struct (s)" allows to declare methods. Preferably, I use explicit "Class (es)" for methods required and P.O.D. "Struct (s)" for only fields.

Yet, I agree that some basic simple operations, like:

assign initial values ("constructor")

make a copy of a structure ("copy constructor)

assign values to an existing structure ("overload assign operator")

Are required, and, in those circumstances, methods for structures, make sense.

Suggestion

Another potential solution is to use P.O.D. structures, but, still conceptually treat them as classes and objects.

Wrap those declarations in a namespace, and, add global functions, for the most important actions.

The code declaration could be similar to this:

namespace Customers
{
  struct CustomerStruct
  {
    char[255] FirstName;
    char[255] LastName;
    int Age;
    bool IsAlive;
    bool IsMarried;
  }; // struct

  CustomerStruct* CreateCustomer
  (
    char* NewFirstName;
    char* NewLastName;
    int NewAge;
    bool NewIsAlive;
    bool NewIsMarried;
  )
  {
    CustomerStruct* NewCustomer = new CustomerStruct();
      NewCustomer->FirstName = NewFirstName;
      NewCustomer->LastName = NewLastName;
      NewCustomer->Age = NewAge;
      NewCustomer->IsAlive = NewIsAlive;
      NewCustomer->IsMarried = NewIsMarried;
    return NewCustomer;
  } // CustomerStruct* CreateCustomer (...)

} // namespace

The code that applies the solution, could be something like this:

#include <Customers>

using Customers;

int main (...)
{
   int ErrorCode = 0;

   CustomerClass* ThisCustomer =
     Customers::CreateCustomer
      ("John", "Doe", 23, true, true);

   // do something with "ThisCustomer"

   delete ThisCustomer;

   return ErrorCode;
} // int main(...)

This alternative approach is better when a huge memory allocation of data is required, or interacting with other low-level shared libraries.

This approach, with some changes, is applied in Game Development.

Extra

Personally, I consider a syntax extension for "C++", or even, a new "C++" based P.L. that solves this issue:

// "Plain Old Data" Structure
// No Methods, No "Functors", allowed
strict struct CustomerStruct
{
  char[255] FirstName;
  char[255] LastName;
  int Age;
  bool IsAlive;
  bool IsMarried;
}; // strict struct

// Object Oriented "Plain Old Data" Structure
// Yes, Methods and "Functors" allowed
relaxed struct CustomerStruct
{
  char[255] FirstName;
  char[255] LastName;
  int Age;
  bool IsAlive;
  bool IsMarried;

  public void Foo();
  public void Bar();

  public (void*) (SomeFunctor) ();
}; // relaxed struct

// Class and Object Oriented
class CustomerClass
{
  public char[255] FirstName;
  public char[255] LastName;
  public int Age;
  public bool IsAlive;
  public bool IsMarried;

  public void Foo();
  public void Bar();
}; // class

Cheers.


问:
How and Why should class modifiers enforce or prevent inheritance and the ability to override
This isn't really related to anything I am working on currently, its more of a question I really couldn't find an answer for.

Class modifiers like MustInherit or NotOverridable to me, seem like they only need to be used in larger programs that have multiple people working on and editing it.

I can see in a situation like that how forcing or preventing people to inherit or override makes sense, but in smaller programs I just don't see why or if these would be used.

Is that basically what these modifiers are for or am I missing the purpose of them.

答:
I can see in a situation like that how forcing or preventing people to inherit or override makes sense, but in smaller programs I just don't see why or if these would be used.

This ("Oh, it's just a small program that I alone am working on, and I know what I'm doing.") is a fallacy.

There has been quite a bit of research done which has found that people can only keep a certain amount of things in mind at a time. By forcing yourself to remember if that function is overridable or not, that's one less thing you can spend on something useful, like the problem at hand. And even if you do remember it (the program is small, after all), then you're spending energy on keeping it in mind - meaning you spend less time programming or are more tired after you're done.

And let's face facts, people don't remember things better as they progress through adulthood. Even if you can remember all of the details of this program today, what about a year from now? 5 years from now? It's good to get into the habit now.

And that ignores the fact that you're human (I presume). People make errors. By marking something as abstract or sealed, you let the computer act as a safety net so you don't go off and extend your class design in terrible ways simply because you mistakenly thought you could/should.