问:
Are there alternatives to using an optional type in a multithreaded environment?
I'm making an MPMC queue in C++, and I would like to find out what the best interface for a try_dequeue method would be (I'm not concerned about its implementation). I'd like to provide a method which does not block if the queue is empty (like my dequeue() method does), but somehow notifies this to the caller.

While I provide a bool empty() const method as well, this unfortunately does no good because for a multithreaded queue doing something along the lines of if(!queue.empty()) queue.dequeue(); provides no guarantees.

What I currently have is T try_dequeue(), which throws an exception if the queue is empty. This seems to offer the most intuitive interface, but an empty queue is hardly an exceptional situation, and that seems an awful lot like using exceptions for control flow.

Another option would be bool try_dequeue(T* t), which would write to t only if the queue was not empty and return if t was written to. After using the exception method above, this seems probably least intrusive, but it would require that T is both default-constructible (or in some manner trivially constructible, so the caller can do T t; queue.try_dequeue(&t);) and assignable.

I wouldn't want to force those requirements on T, though, so perhaps a Java-like approach such as optional<T> try_dequeue() is in order. One of the minor issues with this is that I'd have to implement my own (can't use boost). Perhaps more importantly, it makes the interface seem bloated, in the sense that now I'm now dragging another type in where it would (hopefully) be avoidable, and, much like the situation with STL's set::insert requires us to copy a pair, then "unfold" its arguments, it forces the user into clumsy, long ritual that has to be repeated every time he or she uses the function.

Perhaps I'm worrying too much about optional<T>'s usability, given that it doesn't have any of the more serious problems that the other two approaches do, but I'm wondering, what would be the best approach here? Is it the optional one?

Edit: It occurred to me that there's also a bit of an outlandish bool try_dequeue(std::function<void(T&)>) option which actually seems pretty nice (in fact this one will actually have the most minimal interface you can have, where there's no need for any external logic setting a local T to the returned value). Unfortunately I'd prefer to avoid the overhead incurred by calling an actual std::function, and using a template function template<class F> bool try_deque(const F&) isn't an option either since this is a derived class (from a generic queue interface).

答:
As long as the task is not to design a 100% generic lib for each and every case, only a queue for types "T" under your teams control, I would prefer the bool try_dequeue(T* t) approach, or even better bool try_dequeue(T& t)  (since T* t must never be NULL). By this design, the usage will typically look like this:

```<code>  T t;
  if(try_dequeue(t))
  {
     // do something  with t;
  }
</code>```

and the implementation will look like this:

```<code>  bool try_dequeue(Type &t)
  {
      // ... make things thread-safe
      // ... return false if queue is empty
      // ... find index to your storage array
      t=queueStorage[foundIndex];
      // ... remove element at "foundIndex" from "queueStorage"
      return true;
  }
</code>```

This imposes some requirements on your type T: it will need a "simple" (probably parameterless) ctor, and it needs a "copy assignment operator". A copy constructor won't be enough. For many real-world types, these requirements are easy to fulfill (especially when they are under your control). Note, that according to the rule of three it is most times good idea to implement not only a user defined copy ctor alone, so if your current type T has only such a copy ctor, consider to add a copy assignment operator as well.

Body:
As long as the task is not to design a 100% generic lib for each and every case, only a queue for types "T" under your teams control, I would prefer the bool try_dequeue(T* t) approach, or even better bool try_dequeue(T& t)  (since T* t must never be NULL). By this design, the usage will typically look like this:

  T t;
  if(try_dequeue(t))
  {
     // do something  with t;
  }

and the implementation will look like this:

  bool try_dequeue(Type &t)
  {
      // ... make things thread-safe
      // ... return false if queue is empty
      // ... find index to your storage array
      t=queueStorage[foundIndex];
      // ... remove element at "foundIndex" from "queueStorage"
      return true;
  }

This imposes some requirements on your type T: it will need a "simple" (probably parameterless) ctor, and it needs a "copy assignment operator". A copy constructor won't be enough. For many real-world types, these requirements are easy to fulfill (especially when they are under your control). Note, that according to the rule of three it is most times good idea to implement not only a user defined copy ctor alone, so if your current type T has only such a copy ctor, consider to add a copy assignment operator as well.


问:
How 'child proof' should i write code as a solo programmer?
In our company there once were multiple programmers, now i am the last man standing. I have inherited all the code and i maintain, rewrite, extend (,fix) it.

I always run into this behaviour that i try to make stuff fool proof so that a dummie co-worker couldnt mess up the code. But there are limits to what i can do. I cannot prevent that someone holds a reference to an object. Even java/android system classes give you an object that you are not supposed to hold on to but just use it locally and thats it.

In our company a lot went wrong and i am kind of a burned child, i see possibilities how someone could do the wrong thing and the code keeps crashing and I am asked "why do you write stuff like that"...

Right now i am the only programmer but in the future maybe we have more (again), but right now i kinda restrain myself by spending too much time on trying to figure out how i could write my stuff so that the least amount of mistakes can be made with it. Even tho I would be the one who had to make the mistake.

Like everyone i do make mistakes ofc. So i null-check etc and write limits into the java-docs to remind myself what values i may pass etc. those simple checks are not what im talking about. I am talking about that often i could write a method in a simple and good way but some voice in my head says "oh no, what if SOMEONE would pass a wrong parameter or did this and that with it" and suddenly i find myself encapsulating logic and making stuff more complicated only to add some sort of protection against... dummie programmers with me being the only one possible.

I am NOT working on any open API or shared stuff. There will (most likely) never be any code audits etc. I am the only one using the code and it will stay like that for a long time.

So how do i stop myself from doing this fool-proof coding that costs me too much time and brainpower.

EDIT:
i read the other question + answers.
I understand the whole 'defensive programming' but i wonder when am i taking it too far ? And thats more my problem.

答:
I like the answer of @misterbiscuit, although I'm a Java guy and have very little experience with C (seems some concepts are exchangeable beyond the programming language).

I'd like to amend:

If you write software someone's (my) life could depend on, I'd encourage you to double- and triple-check every fckn value. Otherwise, read on.

Conventions - if null is a valid input-paramter, you need to check it. If, by convention, null is not allowed (but for some special cases), you can assume you won't get it.  There are good books available every developer should have read ("Clean Code", "Effective Java")

Unit-Tests - when changing legacy code, I tend to write unit-tests for the current behaviour. This leads to many tests that seems to be wrong, in fact it is just the behaviour of the production code that made me to write the test that way (to make it green). You could do the same trick, but upfront - write tests that document the current behavior.

Documentation - it's necessary to write down architecture and concepts in a meaningful extent. Nobody reads a 300 pages document before starting coding (except it is called "Java for Beginners"). I like the concepts of arc42, because you can document architecture in 3 pages, if you like. and then add some common rules and you are done. (However, it depends on many more factors of how documentation will be)

ContentLicense: CC BY-SA 3.0


问:
Beginning a sentence with a function name?
Occasionally while typing something up that relates to a case-sensitive programming language I end up starting a sentence with a function name. Now the rules of English state that the first word in a sentence needs to be capitalized; the function name is lowercase, though. If you are wondering what could I be saying that would result in the first word being a function name, take this example:

Your fread implementation is broken. fread needs to return how many bytes were read.

I understand that I could change the second instance of fread to It but I want to know the best way of handling this other than just rewriting the sentence. Should I capitalize the function name? The only way I would like to hear "rewrite the sentence" as an answer is if starting the sentence with a function name violates some English rule that I am not aware of.
Edit: I really thank everyone for these answers. They have changed and improved my insight into the issue. I have learned quite a bit from this. I am very surprised that I did not think of these simple but good solutions.

I do think my stance on alternating the sentence was too tough and now I realize due to these good answers that overall altering the sentence appears to be the best option for dealing with these cases be it adding parenthesis after the function or saying The function before the function name and if available using formatting for the function name.

答:
You can start sentence from description:

The function fread[…]

The method fread[…]

The property breadColor […]


问:
How does Facebook manage to allow a user unlimited sessions?
I could login through the website, android app, iOS app, the browsers on mobile, and when I log out from one, it doesn't log me out of all of them. Traditionally, you would log out of all the services at once because your auth_token would be set to null in the DB. That being said, I don't see a way to do this through Rails and Devise.

I only have two solutions so far.

The first one is to have separate session tokens, and figure out which to use based on a header. However, if you want unlimited number of sessions, you need some unique ID to follow through on. I'm not sure how you'd achieve this.

The second solution is to have a counter in the DB named sessions. It keeps track of how many sessions you currently have logged in. If I'm logged in through the website, Android app and iOS app, it would be 3. Whenever you have more than 1 session open and log-out, the number of sessions would be decremented. If the number of sessions becomes 0, we set the auth_token to null in the DB (nil in Ruby).

The only loop-hole I could see in this is that if someone logs out, is still logged in on some other platform, and is code savvy, they could find the auth_token via previous requests on their browser. Then, they could send it in and continue to use it even though they have technically logged out. I don't necessarily see a problem with this, but I don't know if this is a good way to do it.

Does anyone else have a good suggestion? Is there a better place to post this?

答:
One way to implement this would be to keep a separate authentication token for each browser session, instead of one shared authentication token. You can store that in a browser cookie, which is of course specific to that browser, and selecting the "log out" option would clear that browser cookie (and remove it from the database). Even if somebody were to find an auth_token from previous requests for a specific browser, it wouldn't work after that session has been removed from the server database.

So, short answer, use one authentication token per browser instead of one per user account. How you implement that in your server-side web framework is up to you.


答:
Using the process of elimination.

Assumption - the queue is value-based. The same as std::vector, etc.

Assumption - try_dequeue will remove the value from the queue if the value is available and return the value to the caller. Technically, being value based means that the value is copied or moved to the caller.

The return type cannot be a pointer or a reference. The queue only has values. Once the value is removed from the queue, a pointer or reference cannot be maintained. Therefore a value must be returned.

You sited three potential solutions in reverse order of preference.

throw an exception. (ick)

return std::pair<T, bool> i.e. like std::set

return optional<T>

The last two are quite similar syntactically. Some helper functions could make option 2 more tolerable.

Title: Are there alternatives to using an optional type in a multithreaded environment?

Body:
I'm making an MPMC queue in C++, and I would like to find out what the best interface for a try_dequeue method would be (I'm not concerned about its implementation). I'd like to provide a method which does not block if the queue is empty (like my dequeue() method does), but somehow notifies this to the caller.

While I provide a bool empty() const method as well, this unfortunately does no good because for a multithreaded queue doing something along the lines of if(!queue.empty()) queue.dequeue(); provides no guarantees.

What I currently have is T try_dequeue(), which throws an exception if the queue is empty. This seems to offer the most intuitive interface, but an empty queue is hardly an exceptional situation, and that seems an awful lot like using exceptions for control flow.

Another option would be bool try_dequeue(T* t), which would write to t only if the queue was not empty and return if t was written to. After using the exception method above, this seems probably least intrusive, but it would require that T is both default-constructible (or in some manner trivially constructible, so the caller can do T t; queue.try_dequeue(&t);) and assignable.

I wouldn't want to force those requirements on T, though, so perhaps a Java-like approach such as optional<T> try_dequeue() is in order. One of the minor issues with this is that I'd have to implement my own (can't use boost). Perhaps more importantly, it makes the interface seem bloated, in the sense that now I'm now dragging another type in where it would (hopefully) be avoidable, and, much like the situation with STL's set::insert requires us to copy a pair, then "unfold" its arguments, it forces the user into clumsy, long ritual that has to be repeated every time he or she uses the function.

Perhaps I'm worrying too much about optional<T>'s usability, given that it doesn't have any of the more serious problems that the other two approaches do, but I'm wondering, what would be the best approach here? Is it the optional one?

Edit: It occurred to me that there's also a bit of an outlandish bool try_dequeue(std::function<void(T&)>) option which actually seems pretty nice (in fact this one will actually have the most minimal interface you can have, where there's no need for any external logic setting a local T to the returned value). Unfortunately I'd prefer to avoid the overhead incurred by calling an actual std::function, and using a template function template<class F> bool try_deque(const F&) isn't an option either since this is a derived class (from a generic queue interface).


答:
You can compare this to inline mathematics in publications. You will very rarely see sentences starting with a variable or other inline math.

Thus, I conclude, you should avoid function names in the beginning of a sentence.

Maybe this question provides further details: Is it okay to start a sentence with a Greek letter (variable)?.

Title: Beginning a sentence with a function name?

Body:
Occasionally while typing something up that relates to a case-sensitive programming language I end up starting a sentence with a function name. Now the rules of English state that the first word in a sentence needs to be capitalized; the function name is lowercase, though. If you are wondering what could I be saying that would result in the first word being a function name, take this example:

Your fread implementation is broken. fread needs to return how many bytes were read.

I understand that I could change the second instance of fread to It but I want to know the best way of handling this other than just rewriting the sentence. Should I capitalize the function name? The only way I would like to hear "rewrite the sentence" as an answer is if starting the sentence with a function name violates some English rule that I am not aware of.
Edit: I really thank everyone for these answers. They have changed and improved my insight into the issue. I have learned quite a bit from this. I am very surprised that I did not think of these simple but good solutions.

I do think my stance on alternating the sentence was too tough and now I realize due to these good answers that overall altering the sentence appears to be the best option for dealing with these cases be it adding parenthesis after the function or saying The function before the function name and if available using formatting for the function name.


答:
Each time you login from a device you create a unique session presumably with a unique authentication cookie. This session/authorization is for that device only, but, usually you are allowed other logins and sessions from other devices in parrallel.

I don't no why you think this is not the "normal" behavior as its how Google, Stackoverflow and may other sites handle logins and authentications.

This means I can keep my smartphone logged in to google unaffected by signing on and signing of on my PC.

Title: How does Facebook manage to allow a user unlimited sessions?

Body:
I could login through the website, android app, iOS app, the browsers on mobile, and when I log out from one, it doesn't log me out of all of them. Traditionally, you would log out of all the services at once because your auth_token would be set to null in the DB. That being said, I don't see a way to do this through Rails and Devise.

I only have two solutions so far.

The first one is to have separate session tokens, and figure out which to use based on a header. However, if you want unlimited number of sessions, you need some unique ID to follow through on. I'm not sure how you'd achieve this.

The second solution is to have a counter in the DB named sessions. It keeps track of how many sessions you currently have logged in. If I'm logged in through the website, Android app and iOS app, it would be 3. Whenever you have more than 1 session open and log-out, the number of sessions would be decremented. If the number of sessions becomes 0, we set the auth_token to null in the DB (nil in Ruby).

The only loop-hole I could see in this is that if someone logs out, is still logged in on some other platform, and is code savvy, they could find the auth_token via previous requests on their browser. Then, they could send it in and continue to use it even though they have technically logged out. I don't necessarily see a problem with this, but I don't know if this is a good way to do it.

Does anyone else have a good suggestion? Is there a better place to post this?


问:
Line break before or after binary operator?
While Sun's Java code convention suggests to put line break before the operator, many other guidelines disagree with it. I do not see any obvious pros and cons. Are there advantages of using one of these styles over the other?

String longVarName = a + b + c + d +
        e + f;
```
<p>vs</p>
<pre class="lang-java prettyprint-override"><code>String longVarName = a + b + c + d
        + e + f;
</code>```

答:
Leave the expression on one line, and if it becomes too long, then break it up into smaller expressions:

```<code>days = ((year * months_per_year) + month) * days_per_month + day
</code>```

becomes:

```<code>months = year * months_per_year + month
days = months * days_per_month + day
</code>```

If this isn't possible, then I find it more readable to break before the operator, and have the operator begin directly below the previous assignment (putting it below the variable makes me have to think and recenter, which is annoying given that the goal is to make things easier to read):

```<code>random = years * months_per_year
         + month * days_per_month
         + day * hours_per_day
         + hour * minutes_per_hour
         + minute * seconds_per_minute
         + second
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Leave the expression on one line, and if it becomes too long, then break it up into smaller expressions:

days = ((year * months_per_year) + month) * days_per_month + day

becomes:

months = year * months_per_year + month
days = months * days_per_month + day

If this isn't possible, then I find it more readable to break before the operator, and have the operator begin directly below the previous assignment (putting it below the variable makes me have to think and recenter, which is annoying given that the goal is to make things easier to read):

random = years * months_per_year
         + month * days_per_month
         + day * hours_per_day
         + hour * minutes_per_hour
         + minute * seconds_per_minute
         + second


问:
Count Sort Algorithm efficiency
As I read a book about "Algorithm Analysis", I came across count_sort Algorithm.
However, I have read elsewhere that "Quick Sort/ Merge Sort" are the best and the most efficient sorting algorithms. I found this confusing because the complexity of count_sort is O(n+k), which is better than Mergesort and Quicksort which are O(n ln n).

My question:

What is the problem with this sorting Algorithm?

What are the best sorting Algorithms?

```<code>def count_sort(seq):
    b, c = [], defaultdict(list)
    for x in seq:
        c[x].append(x)

    for k in range(min(c), max(c)+1):
        b.extend(c[k])
    return b
</code>```

答:
Counting sorts fail when there are large key values (the k in the O(n)). This means that if you have a large variety of key values, counting sort will be slow. Radix sort can help solve that problem but it does nothing for other issue. Both counting and radix sort are only valid for integer keys. While not a terribly serious limitation, it does mean that Radix Sort's value for the number of digits in a key should not be considered constant.

There's also the small matter of space complexity and stability of sorting. Radix sort requires a stable sorting algorithm to be used as a subsort. Counting sort is stable, provided that you use a separate input and output structure. If you don't then you wind up with an unstable sort. That is, you may wind up with elements in the wrong order.

"Best" is a very loaded term. There is no "best" sorting algorithm. It will depend on a variety of factors including time complexity, space complexity, ability to parallelize the implementation and the ease of implementation.

Title: Count Sort Algorithm efficiency


问:
Acceptable placement of the composition root using dependency injection (DI) and inversion of control (IoC) containers
I've read in several sources including Mark Seemann's 'Ploeh' blog about how the appropriate placement of the composition root of an IoC container is as close as possible to the entry point of an application.

In the .NET world, these applications seem to be commonly thought of as Web projects, WPF projects, console applications, things with a typical UI (read: not library projects).

Is it really going against this sage advice to place the composition root at the entry point of a library project, when it represents the logical entry point of a group of library projects, and the client of a project group such as this is someone else's work, whose author can't or won't add the composition root to their project (a UI project or yet another library project, even)?

I'm familiar with Ninject as an IoC container implementation, but I imagine many others work the same way in that they can scan for a module containing all the necessary binding configurations.  This means I could put a binding module in its own library project to compile with my main library project's output, and if the client wanted to change the configuration (an unlikely scenario in my case), they could drop in a replacement dll to replace the library with the binding module.

This seems to avoid the most common clients having to deal with dependency injection and composition roots at all, and would make for the cleanest API for the library project group.

Yet this seems to fly in the face of conventional wisdom on the issue.  Is it just that most of the advice out there makes the assumption that the developer has some coordination with the development of the UI project(s) as well, rather than my case, in which I'm just developing libraries for others to use?

答: The beauty of external libraries is that they should do what ever it is they say they would do, while exposing a simple, straight forward interface. How ever complex it actually is to do it, should not be the business of the developer who implements it. If DI actually makes the work of the API developer less complex, then it makes 100% sense to use it, as long as it is used properly and its module is declared at the entry point of the API. In developing an MVC app recently, I abstracted the data layer using a repository pattern and even further abstracted by placing a service layer in between the MVC app a the repository layer, both been Class Library projects. I had an ICache Interface mapped to a Cache Class for my Service Context. I initially implemented it using MVC.Web.Cache, but on a later Iteration I swapped it for System.runtime.cache and you can only imagine how large the scale of that Refactor would have been with out my utilizing DI. So my advice; "Go for it".</p>


问:
Is randomly refactoring code allowed in scrum
Background

My team uses scrum

I have currently no task assigned

There are no more pending task in the backlog

Today is Labor Day for my client.

Not having many things to do today I wanted to start refactoring some code I keep on seeing in the project I am working on, but currently I am not assigned to any sprint task to do any large scale refactoring.

Is it OK in Scrum if I start randomly refactoring code that I have and have not written that always bother me but don't have time other days to fix it because of other days assignments?

What about other days that I have spare time between sprints.

I actually do and believe in continuous refactoring. I always do it on the pieces of code that I am working when assigned a story but what about some other code I see that is not currently related to what I am working on at that moment?

答:
I really don't mean to attack other answers, but is nobody else writing automated tests here?
Here's a fun reading  from Martin Fowler for anyone doing Scrum without proper software engineering practices. Robert C. Martin also says a lot about this here.

So, to my answer... In short, it goes like this:

Yes, "randomly" refactoring code is allowed in Scrum, as long as the team decides that it should be done. (After all, it is self-organizing)

And now for the long answer:

It's evident that leaving more and more technical debt after each Sprint is a recipe for disaster. Soon, everyone will slow down as the code bocomes more messy; every change will be harder to make because the code is so tangled and messy that it takes longer to find the spots to change than to make the actual change. It gets even worse if you have to make a change in a big and messy module that you know nothing about, it becomes impossible to gain/keep productivity when adding/switching people in the project, and so on.

If a team wants to keep its velocity steady, they must be able to keep the code base clean in order to continuously increment the software. Refactoring is a mandatory practice if you want to keep your velocity throughout the project's life cycle, and if you want to mitigate the risk of adding/switching people on the project, and if you want to be able to make changes in modules you know nothing about, and so on.

However, refactoring is a very dangerous activity. I repeat - it is a very dangerous activity. That is, unless you have enough test coverage to be able to safely and freely change the code base. If you can just hit a button to check if nothing broke, refactoring becomes a very safe activity; so safe, in fact, that it is part of the cycle of TDD, which is the practice that allows you to create such a test suite in the first place.

But, as the teams in Scrum are self organizing, in the end your team must decide what is the right thing to do. I hope to have given you some arguments in the case you have to convince anyone. (Give special attention to the links in the first paragraph, and every other article they point to)


问:
Is there a design pattern for splitting up files into smaller files?
I am developing a project where I have to load very large files (upto 50 MB). Currently I am loading these files completely into (consecutive) memory. This has the advantage that I can very easily change bytes at certain locations, because I do not know the structure of all bytes.

However, my intention is to also change the structure, e.g. removing/adding 'chunks'. Now I have the idea to remove the 'known' parts out of it, store them in classes with a data chunk only containing those parts and make a sort of reference list to those chunks.

E.g.:

Original file:

Header

ChunkA 1

ChunkA 2

Intermediate

ChunkB 1

Footer

The result will be:

ChunkA 1 and ChunkA 2 instance.
ChunkB 1 instance

'File' instance and a reference with base offsets + reference to all chunks.

At the end I have to 'recreate' or write the original file (with changes) back.

Is this in general a good idea or is there some design pattern helping me in this?

答:
First, I agree with the sentiment of some of the commenters above that what you need may simply be sensible data structures. Each data structure can fulfill a simple contract to both read in from some byte stream and write out to a byte stream. For files of 50MB size, that may be all you need. Take that into account with the rest of the answer.

However, I feel that you may be trying to pry at some deeper concepts here.

The first that comes to mind is efficiency with buffers. I believe a common trick here is to have preallocated buffer "parts" of a known size and use lists of the buffer "parts". In C#, the use of IList> comes to mind as an efficient wrapper around presumably preallocated arrays. See here. Note that these buffer sizes often have had affinity to disk sector size and memory page size as well. Efficient structure definition up front can allow for interesting optimizations later. For example, the TAR archive format uses a 512 byte header record for this sort of reason. If you're copying a file out of a TAR, your sector boundaries don't get messed up, which can be very nice.

Second, I have to wonder if a study of the design behind the rope for string handling might yield some insight. It follows a similar line of thought. This would be useful depending on your editing strategy.


问:
Does jQuery basically use CSS3 for animation and effects?
I originally started out this question with "what is jQuery, and how does it work", in terms of all that fancy animation, effects, slideshow plugins, etc. I was uncertain as to how JQuery does all that fancy stuff. But after reading around on the internet, I am happy to acknowledge that jQuery is basically a "JavaScript library", and by that, I think it means that jQuery is pure text, of JavaScript code, consisting of public methods, functions, constants etc, with the idea that calling these simple methods or functions can replace loads of JavaScript code, and that its has a nice consistent feel to it.

So am I right in saying that all that fancy animation, effects etc  are not "actually" achieved by JavaScript/jQuery?  They are achieved by using CSS3? And CSS3 is a style sheet language which the browser can understand, and has the capabililites of carrying out those style sheet instructions?

Very fuzzy and ambiguous question, I know, but just trying to get my head round how you get those amazing jQuery animations etc.

答:
You Can also use animate function which available in JQuery Plugin.
      $("#divname").animate({top:"",left:""},speedtime);
And also we have more option in animate which specify about animation type like swing or linear etc..</p>


问:
How does a dependently typed programming language cope with mutability?
I have been investigating on the viability of a "normal" programming language with dependent types. Think for example in Java and add dependent types to it. One difficulty which I have found is that the type of a variable may change when mutated, like in the following piece of pseudo-code:

```<code>let xs = [1, 2, 3]; // The type of xs is List<int, 3>
let ys = [4, 5];    // The type of ys is List<int, 2>
xs.concat(ys);      // We concatenate the lists, so the type of xs is now List<int, 5>
</code>```

This becomes a problem when we mutate a variable inside an if statement:

```<code>let xs = [1, 2, 3]; // The type of xs is List<int, 3>
if random_bool {
    xs.push(4);     // The type of xs is List<int, 4>
}
// The type of xs is unknown, because random_bool is set at runtime
</code>```

Is there any research on this topic? Is it possible to address this issue without renouncing to mutability?

答:
Answer posted by gelisam on the dependent_types subreddit

There are two aspects to your question.

The type of a variable changes as it is mutated

Ambiguous type after a conditional block

An assignment which changes the type of the assigned variable is called a "strong update". If you really want your language to support those, be warned that tracking those type changes will make your type system much more complicated, because your type judgements will need to keep track of the code regions inside which your hypotheses and conclusions are valid.

One such type system is described in Stefan Monnier's paper Statically tracking state with Typed Regions. It's been a while since I have learned about this, but the paper seems to describe a language which has statements for strong update, and yet supports very powerful dependent types, namely the calculus of inductive constructions.

Given the kind of language you are trying to implement, however, you probably can't afford such an increase in your complexity budget. So here's a much simpler solution: use ordinary assignments instead of strong updates!

I think I understand why you think you need strong updates, but you probably don't. Consider the following Java snippet:

```<code>Parent p = new Child1();
p = new Child2();
if (condition) {
  p = new Child3();
}
</code>```

The runtime type of p changes at each assignment, but since Java lacks strong updates, the compile-time type of p remains Parent. There is a tradeoff in the choice of p: a type such as Child1 would have been more precise, and would have allowed more methods to be called on p, but would only allow future assignments to replace p with another value of type Child1 or a subclass thereof. The type Parent allows more flexible assignments, but restricts the available methods to those of Parent.

Similarly, when choosing a type for a mutable variable xs in your dependently-typed language, users could have to choose between a precise type such as ist<int,3> and an imprecise type such as Σ n:Nat. List<int, n>, that is, a dependent pair indicating that the int part of List<int,n> is fixed but the n part can be changed by mutations.

With the former type, some methods would be available, such as those which require the list to be non-empty for example, while other methods would be unavailable, namely those which change the length of the list. With the latter type, only methods which work regardless of the current n could be called, but this time it would be legal to change the length of the list. In particular, it would be legal to change the length of the list inside a conditional block, because the code after the block is already unable to call methods which expect a particular length.

What I am trying to say is that adding mutability to a language with dependent types does not necessarily lead to also adding strong updates, and that a language with the first two features but not the third would be simpler and more familiar than a language with strong updates.

Body:
Answer posted by gelisam on the dependent_types subreddit

There are two aspects to your question.

The type of a variable changes as it is mutated

Ambiguous type after a conditional block

An assignment which changes the type of the assigned variable is called a "strong update". If you really want your language to support those, be warned that tracking those type changes will make your type system much more complicated, because your type judgements will need to keep track of the code regions inside which your hypotheses and conclusions are valid.

One such type system is described in Stefan Monnier's paper Statically tracking state with Typed Regions. It's been a while since I have learned about this, but the paper seems to describe a language which has statements for strong update, and yet supports very powerful dependent types, namely the calculus of inductive constructions.

Given the kind of language you are trying to implement, however, you probably can't afford such an increase in your complexity budget. So here's a much simpler solution: use ordinary assignments instead of strong updates!

I think I understand why you think you need strong updates, but you probably don't. Consider the following Java snippet:

Parent p = new Child1();
p = new Child2();
if (condition) {
  p = new Child3();
}

The runtime type of p changes at each assignment, but since Java lacks strong updates, the compile-time type of p remains Parent. There is a tradeoff in the choice of p: a type such as Child1 would have been more precise, and would have allowed more methods to be called on p, but would only allow future assignments to replace p with another value of type Child1 or a subclass thereof. The type Parent allows more flexible assignments, but restricts the available methods to those of Parent.

Similarly, when choosing a type for a mutable variable xs in your dependently-typed language, users could have to choose between a precise type such as ist<int,3> and an imprecise type such as Σ n:Nat. List<int, n>, that is, a dependent pair indicating that the int part of List<int,n> is fixed but the n part can be changed by mutations.

With the former type, some methods would be available, such as those which require the list to be non-empty for example, while other methods would be unavailable, namely those which change the length of the list. With the latter type, only methods which work regardless of the current n could be called, but this time it would be legal to change the length of the list. In particular, it would be legal to change the length of the list inside a conditional block, because the code after the block is already unable to call methods which expect a particular length.

What I am trying to say is that adding mutability to a language with dependent types does not necessarily lead to also adding strong updates, and that a language with the first two features but not the third would be simpler and more familiar than a language with strong updates.


答:
I am only going to answer for the specific example given:

Your fread implementation is broken. fread needs to return how many bytes were read.

Just replace the first full stop (Period) with a semicolon:

Your fread implementation is broken; fread needs to return how many bytes were read.


答:
Scrum doesn't really say anything about refactoring.

What Scrum does say is that if you don't have any tasks within the sprint to work on, you should support the rest of your team to reach the sprint goal. Even if that means fetching coffee for them.

If your team agrees that refactoring the code is the best way you can support them (and that includes having the infrastructure in place to ensure the refactoring doesn't introduce too many new bugs), then by all means go for it.

Title: Is randomly refactoring code allowed in scrum

Body:
Background

My team uses scrum

I have currently no task assigned

There are no more pending task in the backlog

Today is Labor Day for my client.

Not having many things to do today I wanted to start refactoring some code I keep on seeing in the project I am working on, but currently I am not assigned to any sprint task to do any large scale refactoring.

Is it OK in Scrum if I start randomly refactoring code that I have and have not written that always bother me but don't have time other days to fix it because of other days assignments?

What about other days that I have spare time between sprints.

I actually do and believe in continuous refactoring. I always do it on the pieces of code that I am working when assigned a story but what about some other code I see that is not currently related to what I am working on at that moment?


问:
Alternatives for Agile Scrum
We started following the Agile Scrum methodology and we have completed about 10 sprints.

One observation I had is that not all in the team are taking up the responsibilities of completing the tasks and user stories by themselves and everytime they have to be instructed or allotted with some tasks. Also the estimate they are giving are not very agile.

There is always a need for someone to look after all the user stories, their completion status, tasks that are yet to be done etc and allot them to team members who are not occupied.

I also feel that we would be able to deliver faster if we had one person who would create tasks and assign them to people along with deadlines to complete them (project manager role).

And this is what I feel is missing in Agile Scrum.

Given that the team is not taking up tasks and not risking to take up tight estimates, what are the alternates that we can look for? Or, are there any provisions in Agile Scrum to fasten things?

答:
If you only looked at agile because you were expecting an increased productivity be aware that agile (/scrum) is not a silver bullet. Yes, self empowered teams can become more productive, but they need help.

So get a coach. Agile is like playing chess. It takes 30 minutes to explain the rules and after that you can start playing. But it takes years to reach a reasonable level as a chess player.

Title: Alternatives for Agile Scrum


答:
If you don't have typographic means to distinguish (as per another answer), and maybe even if you do, it can be useful to indicate that you are talking about a function by using parens:

Your fread() implementation is broken.  fread() needs to return how
  many bytes were read.

This helps with "explaining" why it is not capitalised at the beginning of the second sentence, and also helps (in the first sentence) to understand why the proper noun (name of a function) is not capitalised there either.  Since (as a proper noun) it arguably should have been.

("arguably" because we could argue whether fread() is a generic noun or a proper noun).

Overall, the use of parens helps the reader's brain understand why strange words appear and what they are.


答:
Random refactoring makes no sense. What makes sense is refactoring of a code that will introduce most benefits. That means :

fixing a design or architecture problem

improving the implementation

Is it OK in Scrum if I start randomly refactoring code that I have and have not written that always bother me but don't have time other days to fix it because of other days assignments?

From this answer :

Keeping code maintainable needs to be an item on your burn-down list (if you use a Scrum). It is just as important as new development. While it may not seem like something that is "visible to the user", ignoring it increases your technical debt. Down the road when the technical debt piles up enough that your code's lack of maintainability slows down development, the delays in new feature development will be visible to customers.

In my previous work, we had some kind of scrum, with larger sprints (2-3 months). Since we had some delays between sprints (1 month), we used this time to analyze the software, and refactor the code.


问:
What is latent parsing in NLP?
I'm reading a paper describing a NLP work, and I hardly catch the concept of a term, "latent parsing".

Original paper: http://web.stanford.edu/~angeli/papers/2013-acl-temporal.pdf

The figure in the page 6 seems to be helpful (I can't upload the figure because of my reputation)

答:
Let me try to explain what I understand after quickly looking at the paper. "Latent" is used to describe techniques that uncover the hidden meaning of a piece of text (see e.g. http://en.wikipedia.org/wiki/Latent_semantic_indexing). In this paper the authors are using machine learning to do latent semantic parsing of temporal expressions.
Essentially one wants to compute a unique represesentation of a temporal expression, for example "March 14" could mean "March 14th" but also "March 2PM". By using regular expressions one can't tell what "March 14" means but by using estimation one knows that March 14th would be the most likely interpretation of that expression and so get the (most likely) correct parsing.</p>

OwnerDisplayName: Wangjin Yi

Title: What is latent parsing in NLP?


问:
Database design with performance issue and use of views
I am designing database for a school system. I am having to create a lot of tables and a lot of link tables to maintain a structure in the system.

I am trying to maintain foreign integrity and trying to create unique data entry as possible. But this will create problem with queries when I start building out the system. I will have to make a lot of joins and I am afraid that this take a toll on optimization and performance.

In this instance,

I have a student who is taking a course for a subject. While he takes the course he can be borrow a book related to that subject from library.

My tables would be

a. Subjects with: id, name

b. course with: id, name, subject id

c. link table to know that the student is taking the course: id, user id, course id

d. library item table id name

e. a link table to know which library item the student is borrowing: library id, id from c

I am trying to user primary key from c because this will make sure that if the user is no longer taking the course he would not be allowed to borrow a book. The link table will cascade if the relation does not exist between the course and the user.

The problem with this is that. If i need to know the name of the subject that the student has borrowed book for. I have to join four tables. I can simply just add subject id id e to get the subject name. But that is what I hate. If this is really an issue with performance would using views make the queries faster and is it really feasible to implement views in a project.

So I guess my questions in this are,

Is it really a big performance issue to make multiple tables with unique columns. I have heard indexing columns help quite a lot?

Are views helpful in maintaining the relational database and making the queries faster?

And in table c I have not used separate primary key id because I want to make sure that the one student can borrow one item at a time. Is this a good practice?

答:
1 -- should not be a problem until you hit millions of rows. Generally speaking you should start out with a clean "logical" schema and change it when and if you hit a performance problem.

2 -- Views are just "canned sql" querying a view is no different from running the underlying SQL. There are good reasons to use views but performance is not one of them.

3 -- Up to you really, depends on your requirements. (But your example does show an id :-) )


答:
DB systems are fast. Unless you are doing something like web portal for many schools to use your software on the same platform, you should usually have no trouble with a regular HW (provided that you generate the queries in a somewhat sane manner).

That said, if you still have doubts it is not that difficult to create an script that will populate your database with hundreds or thousands of professors, dozens of professors and matters, etc. There you may test your platform and decide if you really need to spend time "tuning" the model (my bet is you will not need to).

In general, it is recommended to avoid doing premature optimization. You may end using days and weeks of efforts in updating something that was ok to begin with. If you design well your system (v.g., an programming layer that abstracts the access to data), if you find later in the development that you have performance issues, you can take on them without having to modify much of your system.

Also, regarding

3.And in table c I have not used separate primary key id because I want to make sure that the one student can borrow one item at a time. Is this a good practice

The "one student can borrow one item" is a business rule. At such, at any time the principal may come to you and say "hey, now we let them borrow two items". I would prepare the model to allow N borrowings and enforce the "one item only" in code (maybe even with a separate class to check the restrictions, allows you to swap the class quickly when needed).

Title: Database design with performance issue and use of views

Body:
I am designing database for a school system. I am having to create a lot of tables and a lot of link tables to maintain a structure in the system.

I am trying to maintain foreign integrity and trying to create unique data entry as possible. But this will create problem with queries when I start building out the system. I will have to make a lot of joins and I am afraid that this take a toll on optimization and performance.

In this instance,

I have a student who is taking a course for a subject. While he takes the course he can be borrow a book related to that subject from library.

My tables would be

a. Subjects with: id, name

b. course with: id, name, subject id

c. link table to know that the student is taking the course: id, user id, course id

d. library item table id name

e. a link table to know which library item the student is borrowing: library id, id from c

I am trying to user primary key from c because this will make sure that if the user is no longer taking the course he would not be allowed to borrow a book. The link table will cascade if the relation does not exist between the course and the user.

The problem with this is that. If i need to know the name of the subject that the student has borrowed book for. I have to join four tables. I can simply just add subject id id e to get the subject name. But that is what I hate. If this is really an issue with performance would using views make the queries faster and is it really feasible to implement views in a project.

So I guess my questions in this are,

Is it really a big performance issue to make multiple tables with unique columns. I have heard indexing columns help quite a lot?

Are views helpful in maintaining the relational database and making the queries faster?

And in table c I have not used separate primary key id because I want to make sure that the one student can borrow one item at a time. Is this a good practice?


答:
Is it really a big performance issue to make multiple tables with unique columns. I have heard indexing columns help quite a lot?

This depends on the DB system. Almost any relational DB system I know of automatically will add an index for primary keys. Some DB systems also add indexes automatically for each FK constraint, some others do not. For foreign key columns to be used in JOINS, it makes a lot of sense to add an index beforehand, and you should check the manual of your DB how it behaves when creating new FK constraints.

Actually, performance depends also on how your select statements look like, a classic "JOIN" should make most DBs use the index, but adding some complex logic to your select statements can break the DBs ability to use the index. For your school system, I would not waste too many thoughts into this as long as you don't suffer from any real performance problems.

Are views helpful in maintaining the relational database and making the queries faster?

Also, this depends on the DB system. Some of them have mechanism for caching or indexing views, some have not. See this SO post for detailed discussion about, for example, MS SQL server. If you really want to know it, try it out and measure. In your situation, I would not introduce any views for solving any "hypothetical" performance problems. I would only introduce views if it helps making some of your queries simpler.

And in table c I have not used separate primary key id because I want to make sure that the one student can borrow one item at a time. Is this a good practice?

To make sure that the one student can borrow one item at a time, you should use a unique contraint on the combined IDs for students and items. This has not much to do with adding a separate primary key (which can be done, or not, there are good reasons for and against doing so, but in your case, I don't expect it to make a big difference).


问:
How to save appointments in database?
There are 2 entities. One is admin. The task of admin is to define slots for appointments which will be taken by applicants.

The admin will choose a default time for the appointments like 10am to 2pm and then 3pm to 5pm.

Now the confusion how to save this information in database.

In a single row which contains start date and time and end date and time and number of applicants allowed for that time slot.

Create multiple rows with each date and time slot. Like if there are 2 slots for 15 days then

day 1 10a - 2p

day 1 3p - 5p

day 2 10a - 2p

day 2 3p - 5p

.....

Which will be a better way to save the appointments?

The second way offers flexibility to edit the appointments but will take multiple rows.

The first way saves rows but is complicated when editing and adding or deleting special slots.

答:
There are 2 entities. One is admin. The task of admin is to define slots for appointments which will be taken by applicants.

admin sounds more like an user that an entity. Of course, user may be an entity (or not if your model does not incorporate authorization information).

I see many nouns there : "The task of admin(user) is to define slots for appointments which will be taken by applicants". Why do you think you only have two entities?

Note that I am not saying that any noun should be an entity. Maybe some nouns can be expressed as a relationship. And maybe some nouns are not specific enough and should be represented by several entities. But it is a good rule of thumb to begin the search for entities.

Anyway, it seems that you may think more about your model.

Title: How to save appointments in database?


问:
A sample Memento pattern: Is it correct?
Following this query on memento pattern, I have tried to put my understanding to test.

Memento pattern stands for three things:

Saving state of the "memento" object for its successful retrieval

Saving carefully each valid "state" of the memento

Encapsulating the saved states from the change inducer so that each state remains unaltered

Have I achieved these three with my design?

Problem

This is a zero player game where the program is initialized with a particular set up of chess pawns - the knight and queen. Then program then needs to keep adding set of pawns or knights and queens so that each pawn is "safe" for the next one move of every other pawn.

The condition is that either both pawns should be placed, or none of them should be placed. The chessboard with the most number of non conflicting knights and queens should be returned.

Implementation
I have 4 classes for this:

protected ChessBoard (the Memento)

```<code>private int [][] ChessBoard;

public void ChessBoard();
protected void SetChessBoard();
protected void GetChessBoard(int);
</code>```

public Pawn This is not related to memento. It holds info about the pawns

```<code>public enum PawnType: int
{
    Empty = 0,
    Queen = 1,
    Knight = 2,
}
//This returns a value that shown if the pawn can be placed safely
public bool IsSafeToAddPawn(PawnType);
</code>```

public CareTaker This corresponds to caretaker of memento

This is a double dimentional integer array that keeps
a track of all states. The reason for having 2D array is to
keep track of how many states are stored and
which state is currently active. An example:

0 -2

1 -1

2 0 - This is current state. With second index 0/

3 1 - This state has been saved, but has been undone

```<code>private int [][]State;
private ChessBoard [] MChessBoard;

//This gets the chessboard at the position requested and assigns it to originator
public ChessBoard GetChessBoard(int);

//This overwrites the chessboard at given position
public void SetChessBoard(ChessBoard, int);

private int [][]State;
</code>```

public PlayGame (This is the originator)

```<code>private bool status;
private ChessBoard oChessBoard;

//This sets the state of chessboard at position specified public
SetChessBoard(ChessBoard, int);

//This gets the state of chessboard at position specified public
ChessBoard GetChessBoard(int);

//This function tries to place both the pawns and returns the status of this attempt
public bool PlacePawns(Pawn);
</code>```

Edit after discussion with Kevin

The way I am trying to apply design patterns to my problems is not correct. In a way it helps me understand "how" to "implement" it. Yes. But then, this is not its ideal usage. I might as well simplify my "learning" problem and use my text book ones.

Also refer to this question on programmers.stackoverflow and all the discussions!

答:
I don't fully agree with your statement about what the Memento pattern stands for.

The idea behind this pattern is that there is an object ("originator") that has an internal state. There is another object (the "caretaker") that wants to perform an action over the originator, but wants to be able to undo the change.

The first thing the Caretaker does is to ask for a Memento object to the Originator (which is a representation of its internal state) and then perform the operation which will change the internal state of the Originator. If the Caretaker is not happy with the result, it can revert the changes in the internal state of the Originator using the Memento. The Originator accepts the Memento and restores its internal state.

Therefore, what you save it's the internal state of the Originator encapsulated in an object called Memento.

In your program the Caretaker should be the one to perform the operations over the Originator and not just a data structure to store states. The only requirement is to store the last Memento to support "Undo". However you can support multiples "Undo" operations with any LIFO data structure where you can "pop" and "push" elements. Therefore, the second index is not needed, but I can imagine you can use it somehow to support "REDO" operations (and then it makes no sense in a zero player game).

In conclusion, I think that your design is wrong although it does make sense to apply the Memento pattern in this problem.


问:
higher order functions equivalent construct in TIOBE top 10 languages
I'm trying to find a language construct equivalent to higher order functions in the top 10 languages from TIOBE index.

Here are my results so far:

C - function pointers

Java - anonymous methods, lambdas

Objective-C - function pointers, selectors, blocks, delegates (as explained here)

C++ - function pointers, lambdas

Basic - [missing]

C# - anonymous methods, delegates, lambdas

Python - [I know it's possible, but don't know how it's called]

PHP - anonymous functions

Perl - [missing]

JavaScript - functions

Could You please help me with missing parts? And eventually correct any mistakes? I'm not looking for workarounds, but for built-in language constructs that allow to pass a function to another function.

答:
Python

In Python, functions are first-class objects, so you can pass them to other functions exactly like any other argument, without any special syntax:

```<code>>>> def applier(f, x, y):
    return f(x, y)

>>> def add(x, y):
    return x + y

>>> applier(add, 1, 2)
3
</code>```

All that is required is that the first argument to applier is a callable object that takes two parameters.

Python does also support "small anonymous functions" called lambda expressions, but they must be a single expression (see e.g. Why doesn't Python allow multi-line lambdas?):

```<code>>>> applier(lambda x, y: x * y, 3, 4)
12
</code>```

Body:
Python

In Python, functions are first-class objects, so you can pass them to other functions exactly like any other argument, without any special syntax:

>>> def applier(f, x, y):
    return f(x, y)

>>> def add(x, y):
    return x + y

>>> applier(add, 1, 2)
3

All that is required is that the first argument to applier is a callable object that takes two parameters.

Python does also support "small anonymous functions" called lambda expressions, but they must be a single expression (see e.g. Why doesn't Python allow multi-line lambdas?):

>>> applier(lambda x, y: x * y, 3, 4)
12


答:
I hacked a basic example with Mysql Workbench in 5 minutes

You can have different methods to keep track of borrowed and returned, I showed an example with borrow_history to keep history and you can manage if library_items are out or not via "borrowed_until" field. You can also track how many books a student took out via "borrowed", that you can += 1 upon borrowing and -= 1 upon returning.

You can compare this with Wordpress Database Schema and see how much smaller your database schema is.

You don't have to worry too much about the schema until you hit few million rows, and then correct indices will take care of most of the stuff for you. If you get much larger, you may want to try some Nosql solutions in tandem.

Try to check some business logic that you mentioned in your application, doing it on the database can be more difficult and may require learning stored procedures, triggers, etc. I think it would benefit you to learn those after you master database schema design and indexing techniques.

You can worry about a lot of things, but "premature optimization is the root of all evil". Joins will not be a problem until you go really crazy with it, maybe up to 10 joins for a query may start causing problems. But if your database is small, it won't matter. Obviously you must index the foreign keys, but I am assuming you would know that. Only way to figure out these things is to create fake data and test how hey perform.


问:
What are the disadvantages of a "simple factory"?
I am reading the book »Head First Design Patterns« from O'Reilly. Before explaining the Factory Method Pattern, they introduce a Simple Factory first.

They are using the example of a pizzeria. In a first step they show the problem:

```<code>Pizza orderPizza(string type) {
  Pizza pizza;
  if (type.equals("Pepperoni") { pizza = new PepperoniPizza(); }
  else if (type.equals("Salmon") { pizza = new SalmonPizza(); }
  // ... and so on

  pizza.Prepare();
  pizza.Bake();
  pizza.Cut();
  pizza.Pack();
  return pizza;
}
</code>```

The obvious problem is that you had to change Pizzeria whenever you add or remove a Pizza.

Hence they introduce a "Simple Factory Idiom" first. They move the creating part into a class "SimplePizzaFactory". Now you don't need to modify Pizzeria anymore when adding or removing a Pizza.

Then they say that this approach isn't that good, when you have more than one pizzeria (in several towns).

I don't really understand their reasoning. They give the following example code and then they say that each pizzeria wouldn't be using the procedure as implemented above but were using different methods in order to "bake", "cut" and "pack" the pizza.

```<code>BerlinPizzaFactory berlinFactory = new BerlinPizzaFactory();
Pizzeria berlinPizzeria = new Pizzeria(berlinFactory);
berlinPizza.Order("Pepperoni");
</code>```

Instead of using the Simple Factory, they suggest using the Factory Method Pattern.

First, I don't see why the BerlinPizzeria is supposed to not using the procedure. It's still a Pizzeria and when you call Order, you're using the same procedure.

My best guess is that they are implying that you are able to implement, let's say, a cafeteria (I'm deliberately using something entirely different to make my point) and use the factory (as it is independent of the pizzeria) and prepare the pizza in a way you want to.

But even when using the Factory Method Pattern, nobody forces you to use the default procedure. It's even simpler to "hide" that you're doing it differently. Their code examples are given in Java and Java methods are virtual by default. So I would be able to implement BerlinPizzeria and override Order (or had to explicitly declare the method as final). The client, however, wouldn't notice that my BerlinPizzeria is doing things differently.

In conclusion I don't see any significant difference between a Simple Factory and the Factory Method Pattern. The only advantage of the Factory Method Pattern I'm seeing is that you would save a few classes (namely, the 'outsourced' factories).

So, what is really the disadvantages of a Simple Factory and why isn't is a good idea to 'outsource' the creating part?

Or what is really the advantage of the Factory Method pattern and why is it a good idea to force the creating part being implemented in the subclass?

答:
First of all, I've read that book and I love it.

The classic implementation of the Simple Factory is just a bunch of "static create" methods encapsulated into one class.

You can argue that you separate the implementation of the class from its creation, but that's it. There is no further advantage and even that statement is questionable. In my point of view, you're just separating some creation static methods into a different file.

In most real cases, you end up with a huge "file" which produces not only Pizzas, but also many other unrelated objects like Burguers, Icecreams, ... so you break the single responsibility principle. This is because at the beginning, you just have a couple of create methods of most things, so the "natural" thing is to group them so they don't feel alone in one small Simple Factory class.

Therefore, the main disadvantages are cluttering. In most cases you end up with huge files or with many small files.

However, the main thing is that the Simple Factory is not a design pattern, is just a convention which can be useful is some cases (e.g. unit testing). In most cases you just need a couple of create methods which can be included in the same class (you don't need an external class for that).

If you have lots of create methods for one single class, you've got a big problem: either this class is doing too much, you think that passing parameters is a bad thing or any other random reason.

The Factory Method, unlike the Simple Factory, uses inheritance to solve the problem of creating objects without specifying their exact classes.

Wait for the Proxy chapter. A Proxy (in brief) is an object that "stands for" another. In this case the Factory Method can be useful because you create an instance which can be the Proxy or the real Object itself.


问:
Start reading Ruby (on Rails) code
I'm an experienced developer which quite some experience in meta programming. I just found my way to Ruby and want to understand more of Rails (and related) project internals. Even if I understand the high level concepts, it's hard to get an overview of those projects. I wonder how other people approach that problem? How would you for example approach the Mongoid source code to get a good understanding of it's internals?</p>

答:
When you study the Rails implementation, you can broadly "cut it up" into several big pieces, and work on them one by one. I would take them in this order:

Active Support -- utilities and helper classes which are used throughout the framework.

Active Record -- the object-relational mapping layer.

Action Pack -- this is the "core" of Rails; it handles HTTP requests, routes them to a controller and method, invokes the controller, then renders the template.

Command-line tools, initialization code, interface with the underlying web server.

Active Support and Active Record both "stand alone" and are not dependent on the rest of the framework, which makes them easier to decipher. That is why I recommend you start with those two. When studying Active Record, you will also want to look at the code for the ARel gem -- AR doesn't make much sense without it.

When you are ready to tackle Action Pack, you might want to start with the request router, which is also fairly "stand-alone".

When studying each part, read the RDocs first. Rails is well-documented, and before you dive into the code, that documentation will give you a good overview of what classes are there, and what each one is for. That will also help you choose a good place to start reading the code.

Title: Start reading Ruby (on Rails) code


问:
Should I throw guard exceptions that will be thrown by internal methods anyway?
I have some fairly simple code (C#):

```<code>    /// <summary>
    /// Truncates a string to a maximum length.
    /// </summary>
    /// <param name="value">     The string to truncate. </param>
    /// <param name="maxLength"> The maximum length of the string. </param>
    /// <returns>
    /// The original string if its length is less than or equal to max length, else a truncated
    /// string of length maxLength.
    /// </returns>
    public static string Truncate(string value, int maxLength)
    {
        if(maxLength <= 0) throw new ArgumentOutOfRangeException("maxLength");

        if (string.IsNullOrEmpty(value)) return value;

        return value.Length <= maxLength ? value : value.Substring(0, maxLength);
    }
</code>```

It's clear that if maxLength is less than 0, I can't use it as a string length, and so I am currently using a guard statement to prevent invalid maxLength values.

My question is: is it good or bad practice to use this guard statement, when value.Substring will throw the same exception anyway? Is it just wasted code?

答:
It comes down to the contracts that your methods obey.

Your example code doesn't show any exception specifications, so technically nobody should assume anything about what happens for maxLength < 0 - it doesn't even matter whether you throw an exception at all.

If you do want that behaviour to be part of your semantics, it should be documented. Then whether or not to throw the exception yourself comes down to what the contract of the built-in method is. It that one is guaranteed to throw this exception, you can simply rely on that (although some would argue that throwing the exception explicitly is still better because of readability and fail-early concerns). If it isn't, you must throw the exception yourself.


答:
Generally the purpose behind throwing the exception yourself is to provide your own personal exception.  For example, if Truncate were a method available to use in a library, lets call it ABC, it might be nice to have all your exceptions fall under a base exception called ABCException which also comes from the library.  In other words, for any problems caused by library ABC, you can optionally catch it using the base exception ABCException.  This is extremely useful to identify problems coming from a specific library.

Another reason to perform your own check is for a "sanity check".  In other words, yes, perhaps Substring throws this exception, but should you decide tomorrow that something should be done prior to performing the actual Substring call, your code may throw a different and uncaught exception instead.  This may make debugging the problem that much more difficult since you may discard the possibility of the problem being in Truncate because of the fact that Truncate is supposed to throw another exception in such circumstances.  Call it what you will, but I like to call it defensive programming.  Is this likely?  No, but if it is only going to cost you 10 seconds to add, I'd say to go ahead and add it.

Note that I wouldn't add checks like these unless they were public methods and therefore available to be called by anyone.  Also, in circumstances in which the method is specifically documented as such, I wouldn't even perform checks.  If the caller fails to respect the documentation for said method, it is the caller's responsibility, not yours.

Also, if I may make a minor optimization, the contents of the if statement should be the most likely scenario rather than the least likely.  That said, I would rewrite it:

```<code>public static string Truncate(string value, int maxLength)
{
    if(maxLength > 0 && !string.IsNullOrEmpty(value))
        return value.Length <= maxLength ? value : value.Substring(0, maxLength);
    else
        throw new ArgumentOutOfRangeException("maxLength");
}
</code>```

Hope that helps!

Title: Should I throw guard exceptions that will be thrown by internal methods anyway?

Body:
I have some fairly simple code (C#):

```<code>    /// <summary>
    /// Truncates a string to a maximum length.
    /// </summary>
    /// <param name="value">     The string to truncate. </param>
    /// <param name="maxLength"> The maximum length of the string. </param>
    /// <returns>
    /// The original string if its length is less than or equal to max length, else a truncated
    /// string of length maxLength.
    /// </returns>
    public static string Truncate(string value, int maxLength)
    {
        if(maxLength <= 0) throw new ArgumentOutOfRangeException("maxLength");

        if (string.IsNullOrEmpty(value)) return value;

        return value.Length <= maxLength ? value : value.Substring(0, maxLength);
    }
</code>```

It's clear that if maxLength is less than 0, I can't use it as a string length, and so I am currently using a guard statement to prevent invalid maxLength values.

My question is: is it good or bad practice to use this guard statement, when value.Substring will throw the same exception anyway? Is it just wasted code?

Body:
Generally the purpose behind throwing the exception yourself is to provide your own personal exception.  For example, if Truncate were a method available to use in a library, lets call it ABC, it might be nice to have all your exceptions fall under a base exception called ABCException which also comes from the library.  In other words, for any problems caused by library ABC, you can optionally catch it using the base exception ABCException.  This is extremely useful to identify problems coming from a specific library.

Another reason to perform your own check is for a "sanity check".  In other words, yes, perhaps Substring throws this exception, but should you decide tomorrow that something should be done prior to performing the actual Substring call, your code may throw a different and uncaught exception instead.  This may make debugging the problem that much more difficult since you may discard the possibility of the problem being in Truncate because of the fact that Truncate is supposed to throw another exception in such circumstances.  Call it what you will, but I like to call it defensive programming.  Is this likely?  No, but if it is only going to cost you 10 seconds to add, I'd say to go ahead and add it.

Note that I wouldn't add checks like these unless they were public methods and therefore available to be called by anyone.  Also, in circumstances in which the method is specifically documented as such, I wouldn't even perform checks.  If the caller fails to respect the documentation for said method, it is the caller's responsibility, not yours.

Also, if I may make a minor optimization, the contents of the if statement should be the most likely scenario rather than the least likely.  That said, I would rewrite it:

public static string Truncate(string value, int maxLength)
{
    if(maxLength > 0 && !string.IsNullOrEmpty(value))
        return value.Length <= maxLength ? value : value.Substring(0, maxLength);
    else
        throw new ArgumentOutOfRangeException("maxLength");
}

Hope that helps!


答:
I think it is a good idea to take query performance into consideration early in the design phase, but at some point, your database has to hold the data required by your application. Even if your table design isn't optimal, you can change it later (easier said than done), improve indexing, cache query results (different databases offer their own solutions), create denormalized tables that hold pre-calculated/joined report results, add more hardware.

Is it really a big performance issue to make multiple tables with
  unique columns. I have heard indexing columns help quite a lot?

At some point linking many tables will cause a performance problem; however I think it is more than 4. Indexing will help. At some point too many indexes will limit performance on data changes because all those indexes need to be maintained. Since this is for a school system and student's courses change with each term, you can archive past terms, so this database may not grow that much. No one is going to check out a book for a course they tool last year.

Are views helpful in maintaining the relational database and making
  the queries faster?

Not really. They're just an object in the database that holds all the text for your query. You need to design high-performance queries regardless of where they are stored. It can make reuse easier, but beware, having multiple levels of views (a view of a view of a view) will hurt performance in most RDBMS. Databases don't reuse code as well as other languages.

And in table c I have not used separate primary key id because I want
  to make sure that the one student can borrow one item at a time. Is
  this a good practice?

You can still use a separate primary key along with another unique constraint. Since you're relying on this unique constraint to hand this requirement, if you have to include or exclude another column(s), you don't have to change the relationships with other tables or possibly have to rebuild them. Currently, you're not relying on this to join to another table.


答:
As delnan said in comments, this has little to do with mutability. Let's see how one could type their example.

```<code>let xs = [3,2,1] in (if random_bool then 4:xs else xs)
</code>```

In a dependently-typed language, if-then-else is a special case of elimBool, the eliminator for boolean-valued expressions whose type is:

```<code>elimBool :: (P : Bool -> Type) (t : P true) (f : P false) (b : Bool) -> P b
</code>```

Indeed: if we take P a constant, we recover the typing principle for if-then-else modulo permutation of the arguments.

Now, in this instance we do not really have an if-then-else expression given that the two branches don't have the same type. We have a full-blown elimBool one. And it can be typed the following way:

Start by defining the appropriate predicate Pred describing the type of the expression:

```<code>Pred :: Bool -> Type
Pred b = elimBool (\ _ -> Type) List<int, 4> List<int, 3> b
</code>```

or, equivalently given that Pred's predicate is constant, we can use an if-then-else expression:

```<code>Pred :: Bool -> Type
Pred b = if b then List<int, 4> else List<int, 3> b
</code>```

In other words, the predicate inspects its argument and says that it expects either a list of length 4 or one of length 3 depending on whether the argument is true or false.

The expression itself can then be written:

```<code>Exp :: Pred random_bool
Exp = elimBool Pred (4 : xs) xs random_bool
</code>```

Indeed, according to elimBool's type the first branch 4 : xs has to have type Pred true which is precisely List<int, 4> whilst the second one has type Pred false which is equal to List<int, 3>.

Title: How does a dependently typed programming language cope with mutability?

Body:
I have been investigating on the viability of a "normal" programming language with dependent types. Think for example in Java and add dependent types to it. One difficulty which I have found is that the type of a variable may change when mutated, like in the following piece of pseudo-code:

```<code>let xs = [1, 2, 3]; // The type of xs is List<int, 3>
let ys = [4, 5];    // The type of ys is List<int, 2>
xs.concat(ys);      // We concatenate the lists, so the type of xs is now List<int, 5>
</code>```

This becomes a problem when we mutate a variable inside an if statement:

```<code>let xs = [1, 2, 3]; // The type of xs is List<int, 3>
if random_bool {
    xs.push(4);     // The type of xs is List<int, 4>
}
// The type of xs is unknown, because random_bool is set at runtime
</code>```

Is there any research on this topic? Is it possible to address this issue without renouncing to mutability?

Body:
As delnan said in comments, this has little to do with mutability. Let's see how one could type their example.

let xs = [3,2,1] in (if random_bool then 4:xs else xs)

In a dependently-typed language, if-then-else is a special case of elimBool, the eliminator for boolean-valued expressions whose type is:

elimBool :: (P : Bool -> Type) (t : P true) (f : P false) (b : Bool) -> P b

Indeed: if we take P a constant, we recover the typing principle for if-then-else modulo permutation of the arguments.

Now, in this instance we do not really have an if-then-else expression given that the two branches don't have the same type. We have a full-blown elimBool one. And it can be typed the following way:

Start by defining the appropriate predicate Pred describing the type of the expression:

Pred :: Bool -> Type
Pred b = elimBool (\ _ -> Type) List<int, 4> List<int, 3> b

or, equivalently given that Pred's predicate is constant, we can use an if-then-else expression:

Pred :: Bool -> Type
Pred b = if b then List<int, 4> else List<int, 3> b

In other words, the predicate inspects its argument and says that it expects either a list of length 4 or one of length 3 depending on whether the argument is true or false.

The expression itself can then be written:

Exp :: Pred random_bool
Exp = elimBool Pred (4 : xs) xs random_bool

Indeed, according to elimBool's type the first branch 4 : xs has to have type Pred true which is precisely List<int, 4> whilst the second one has type Pred false which is equal to List<int, 3>.


答:
A higher order function is a function that takes another function as argument. A well-known higher order function is map, which performs an action on each element in a collection, e.g.:

-- Haskell
map (\x -> 2 * x) [1, 2, 3, 4, 5] -- => [2, 4, 6, 8, 10]
```

Higher order functions require that you can pass a function around as a first-class value, just as you can pass around numbers, strings, or other objects. This is either done by not making functions special at all (i.e. they are just ordinary objects with special syntax for creating them), or by providing special syntax to obtain a reference to a function. There might also be a syntax for anonymous functions (lambdas), but this is not strictly necessary in order to have higher order functions.

In object oriented languages, it's interesting to note that objects and closures are equivalent to each other. In fact, many languages represent first-class functions as an object with a method called apply() or similar. Even before Java got lambdas, first-class functions could be implemented very verbosely by passing objects around, and anonymous classes are very similar to actual lambdas. The Command Pattern is essentially an encoding of first-class functions into an OOP context. So any OOP language can have higher order functions, but first class functions tend to involve an unreasonable amount of ceremony.

Languages with computed GO TOs are also equivalent to (actually, even more powerful than) first-class functions. While such languages tend to lack many type system guarantees and make writing obscure spaghetti code easy, they could be viewed as also providing first-class functions.

C: has function pointers (i.e. first-class functions) and also supports higher-order functions. However, it does not have closures.

Java: does OOP and therefore supports the Command Pattern. It also had anonymous classes for a while, which is a kind of lambda. With Java 8, it gained real lambdas and syntax to pass methods around as ordinary objects. Closures are limited.

C++: has everything C has, plus the Command Pattern due to OOP. It gained various forms of lambdas in the C++11 revision. Closures are explicit, and limited by the memory management scheme.

Python: Is an OOP language, but also has a number if Lisp influences (Lisp is the original functional programming language). Functions are just objects with fancy syntax. The function call operator is actually translated to a method call, which means that user-defined objects can also be used like a function. There is also a form of anonymous functions (lambda expressions), but they are ridiculously limited. All functions are closures, but they sometimes have to be explicit due to Python's scoping rules.

JavaScript: Is the same story as with Python, except that it lacks operator overloading, and doesn't impose restrictions on lambdas. Closures work as expected.

Perl: Supports both object oriented and functional paradigms. You can obtain a reference to a named function like $code_ref = \&function_name, and can call such references like $code_ref->(@arguments), which is equivalent to function_name(@arguments). Method calls can be performed by a run-time name, so that $object->method() is the same as $name = "method"; $object->$name(). Method resolution can be carried out to produce a code reference like $code_ref = $object->can("method"). Anonymous functions are supported: $code_ref = sub { ... }. Furthermore, the function call operator can be overloaded for objects. All functions are closures.

I can't comment on C#, PHP and the various BASIC dialects.

Title: higher order functions equivalent construct in TIOBE top 10 languages

Body:
I'm trying to find a language construct equivalent to higher order functions in the top 10 languages from TIOBE index.

Here are my results so far:

C - function pointers

Java - anonymous methods, lambdas

Objective-C - function pointers, selectors, blocks, delegates (as explained here)

C++ - function pointers, lambdas

Basic - [missing]

C# - anonymous methods, delegates, lambdas

Python - [I know it's possible, but don't know how it's called]

PHP - anonymous functions

Perl - [missing]

JavaScript - functions

Could You please help me with missing parts? And eventually correct any mistakes? I'm not looking for workarounds, but for built-in language constructs that allow to pass a function to another function.

Body:
A higher order function is a function that takes another function as argument. A well-known higher order function is map, which performs an action on each element in a collection, e.g.:

-- Haskell
map (\x -> 2 * x) [1, 2, 3, 4, 5] -- => [2, 4, 6, 8, 10]

Higher order functions require that you can pass a function around as a first-class value, just as you can pass around numbers, strings, or other objects. This is either done by not making functions special at all (i.e. they are just ordinary objects with special syntax for creating them), or by providing special syntax to obtain a reference to a function. There might also be a syntax for anonymous functions (lambdas), but this is not strictly necessary in order to have higher order functions.

In object oriented languages, it's interesting to note that objects and closures are equivalent to each other. In fact, many languages represent first-class functions as an object with a method called apply() or similar. Even before Java got lambdas, first-class functions could be implemented very verbosely by passing objects around, and anonymous classes are very similar to actual lambdas. The Command Pattern is essentially an encoding of first-class functions into an OOP context. So any OOP language can have higher order functions, but first class functions tend to involve an unreasonable amount of ceremony.

Languages with computed GO TOs are also equivalent to (actually, even more powerful than) first-class functions. While such languages tend to lack many type system guarantees and make writing obscure spaghetti code easy, they could be viewed as also providing first-class functions.

C: has function pointers (i.e. first-class functions) and also supports higher-order functions. However, it does not have closures.

Java: does OOP and therefore supports the Command Pattern. It also had anonymous classes for a while, which is a kind of lambda. With Java 8, it gained real lambdas and syntax to pass methods around as ordinary objects. Closures are limited.

C++: has everything C has, plus the Command Pattern due to OOP. It gained various forms of lambdas in the C++11 revision. Closures are explicit, and limited by the memory management scheme.

Python: Is an OOP language, but also has a number if Lisp influences (Lisp is the original functional programming language). Functions are just objects with fancy syntax. The function call operator is actually translated to a method call, which means that user-defined objects can also be used like a function. There is also a form of anonymous functions (lambda expressions), but they are ridiculously limited. All functions are closures, but they sometimes have to be explicit due to Python's scoping rules.

JavaScript: Is the same story as with Python, except that it lacks operator overloading, and doesn't impose restrictions on lambdas. Closures work as expected.

Perl: Supports both object oriented and functional paradigms. You can obtain a reference to a named function like $code_ref = \&function_name, and can call such references like $code_ref->(@arguments), which is equivalent to function_name(@arguments). Method calls can be performed by a run-time name, so that $object->method() is the same as $name = "method"; $object->$name(). Method resolution can be carried out to produce a code reference like $code_ref = $object->can("method"). Anonymous functions are supported: $code_ref = sub { ... }. Furthermore, the function call operator can be overloaded for objects. All functions are closures.

I can't comment on C#, PHP and the various BASIC dialects.


问:
In MVC design, do I use a base class over an interface?
In web MVC most designs I've seen, (just choosing model layer as an example) the domain problem class, say students, always inherits the superclass "Model."  The name is irrelevant, but why do they always inherit classes instead of interfaces?

I've seen others that have interface -> abstract class -> concrete class.  But, I don't know why I'd choose a class over an inteface.

Will I need to execute something in the constructor of the superclass
in MVC? Some other method?

I know of no mutual functionality that
needs an implementation beforehand, but that is probably
inexperience?  I don't now.

Why not just an interface to enforce my
API?

I have seen other answers.  I have not seen it in the specific context of MVC design, however.

Using PHP if it matters.

答:
Let's explore the differences between using an interface vs a base class:

If I'm using an interface, that means I need to also implement the, for example, connection logic for each class which wants to connect to the DB.  That is a huge pain.

However, if I just subclass a base class (which already provides connection method), then I don't need to keep on implementing it myself.  I can just focus on the specialized behavior of the class I'm writing.

So, in cases like this, using a base class over an interface saves me from repeating myself ad nauseum.