问:
Rails validation: Which method is preferred
In Ruby on Rails there are two ways to validate, for instance, the presence of input fields. Say I want to make sure the user has filled out my fields called value and name. I could put in my model either:

```<code>validates_presence_of :value, :name

## Or

validates :value, presence: true
validates :name, presence: true
</code>```

In this situation judging strictly by DRYness, method 1 looks better, but in the application I'm working on I have the following validation:

```<code>validates_presence_of :value, :name
validates_uniqueness_of :value
validates_numericality_of :value, :only_integer => true

## Which I can refactor to:

validates :value, presence: true, uniqueness: true, numericality: { only_integer: true }
validates :name, presence: true
</code>```

And in this case the second method looks better.

Is there a generally preferred method, or is it case-by-case? (If it's case-by-case, wouldn't it be confusing for maintainers?)

Is it safe to adopt one method for the entire application? (If so, which one should I adopt?)

答:
Maintainability trumps all. Unless you have a pressing reason not to, follow the conventions as they appear in the reference material.

In this case, the first Google hit is the documentation for validations at rubyonrails.org, which shows a strong preference to the validates form. The only counter example I could find was validates_associated, which makes sense as it does not actually validate the current object.

I would recommend picking one way to do it, as it facilitates visually scanning the code.

Personally, I prefer the flexibility of the validates version.


问:
What might be a good way to get hands on experience with Object Oriented PHP
I am a Computer Science student. I took a course on OOP, and I understand the concepts (classes, extending, encapsulation, etc). I'm also a web developer, have been doing it for about three years; I've worked with Laravel and Codeigniter, but never really created classes my self. I want to hear what might be a good way to be excellent in OOP, applying all the knowledge and gaining experience at the same time.</p>

答: In the words of Nike and (recently) Shia LaBeouf, just do it. There are plenty of free resources online, though I utilized portions of this book to get me started. Just start messing around with the class-related syntax at first to get a feel for it and build some simple classes (I started with a class or two that did fantasy football point calculations). When you feel more confident, try building a small, simple application. As you immerse yourself into the task of actually building something, the right questions will arise and you will find the answers online, in the php documentation, by looking at other code, in that book or another book, or directly from others. You may even figure it out yourself and will become better at figuring it out yourself as you gain more experience. If you already have some object oriented experience, you really just need to learn PHP's syntax, and it is not that dissimilar from other class-based OO languages like Java. To summarize, building applications whether it be in your own time or professionally will really develop your skills. Working with and looking at frameworks like Laravel may help as well though I did not find this as helpful when I was initially starting out. Hope this helps! Good luck!</p>

ContentLicense: CC BY-SA 3.0


问:
Code cleanup methods and/or code coverage tools
I have an application at work, which I started work on about 7 years ago. This was my first engagement in ASP.NET web applications, and coming from a Win32 background I had a hard time adjusting.

All this time, both the project and myself have "matured" and now most parts of it are well defined, properly structured and readable. However, there is a significant piece of it, that is "old junk". By that I mean old obsolete code, that was not working well, or was not properly structured, which has been replaced, but left in the source files instead of being removed. I must note here, that I was not the sole developer, but did most of the coding throughout.

What I want to do, is whenever I have free time at work, to remove the old obsolete and unused code. Are there any techniques/methodologies that I can use/follow in order to do this more efficiently? Any tools perhaps?

EDIT: (clarification based on feedback)
The code I am talking about is not used anywhere, and is not called from anywhere in the project. What I need is way to find out where the code resides, since we are talking about a large codebase. So something in terms of code coverage tools would help. Any suggestions for asp.net projects? (the particular case is in Web Site project form)

答:
I think removing dead code broadly falls under refactoring's definition of "process of changing a computer program's source code without modifying its external functional behavior in order to improve some of the nonfunctional attributes of the software".

There are some well-known books about refactoring.

Maybe a code coverage tool can be helpful in your special case.

ContentLicense: CC BY-SA 2.5


问:
Is the semantic contract of an interface (OOP) more informative than a function signature (FP)?
It is said by some that if you take SOLID principles to their extremes, you end up at functional programming. I agree with this article but I think that some semantics are lost in the transition from interface/object to function/closure, and I want to know how Functional Programming can mitigate the loss.

From the article:

Furthermore, if you rigorously apply the Interface Segregation Principle (ISP), you'll understand that you should favour Role Interfaces over Header Interfaces.

If you keep driving your design towards smaller and smaller interfaces, you'll eventually arrive at the ultimate Role Interface: an interface with a single method. This happens to me a lot. Here's an example:

```<code>public interface IMessageQuery
{
    string Read(int id);
}
</code>```

If I take a dependency on an IMessageQuery, part of the implicit contract is that calling Read(id) will search for and return a message with the given ID.

Compare this to taking a dependency on its equivalent functional signature,  int -> string. Without any additional cues, this function could be a simple ToString(). If you implemented IMessageQuery.Read(int id) with a ToString() I may accuse you of being deliberately subversive!

So, what can functional programmers do to preserve the semantics of a well-named interface? Is it conventional to, for example, create a record type with a single member?

```<code>type MessageQuery = {
    Read: int -> string
}
</code>```

答:
Pretty much all statically-typed functional languages have a way to alias basic types in a way that requires you to explicitly declare your semantic intent.  Some of the other answers have given examples.  In practice, experienced functional programmers need very good reasons to use those wrapper types, because they hurt composability and reusability.

For example, say a client wanted an implementation of a message query that was backed by a list.  In Haskell, the implementation could be as simple as this:

```<code>messages = ["Message 0", "Message 1", "Message 2"]
messageQuery = (messages !!)
</code>```

Using newtype Message = Message String this would be much less straightforward, leaving this implementation looking something like:

```<code>messages = map Message ["Message 0", "Message 1", "Message 2"]
messageQuery (Id index) = messages !! index
</code>```

That might not seem like a big deal, but you either have to do that type conversion back and forth everywhere, or set up a boundary layer in your code where everything above is Int -> String then you convert it to Id -> Message to pass to the layer below.  Say I wanted to add internationalization, or format it in all caps, or add logging context, or whatever.  Those operations are all dead simple to compose with an Int -> String, and annoying with an Id -> Message.  It's not that there are never cases where the increased type restrictions are desirable, but the annoyance had better be worth the trade off.

You can use a type synonym instead of a wrapper (in Haskell type instead of newtype), which is much more common and doesn't require the conversions all over the place, but it doesn't provide the static type guarantees either like your OOP version, just a bit of enapsulation.  Type wrappers are mostly used where the client isn't expected to manipulate the value at all, just store it and pass it back.  For example, a file handle.

Nothing can prevent a client from being "subversive."  You're just creating hoops to jump through, for every single client.  A simple mock for a common unit test often requires weird behavior that doesn't make sense in production.  Your interfaces should be written so they don't care, if at all possible.

Body:
Pretty much all statically-typed functional languages have a way to alias basic types in a way that requires you to explicitly declare your semantic intent.  Some of the other answers have given examples.  In practice, experienced functional programmers need very good reasons to use those wrapper types, because they hurt composability and reusability.

For example, say a client wanted an implementation of a message query that was backed by a list.  In Haskell, the implementation could be as simple as this:

messages = ["Message 0", "Message 1", "Message 2"]
messageQuery = (messages !!)

Using newtype Message = Message String this would be much less straightforward, leaving this implementation looking something like:

messages = map Message ["Message 0", "Message 1", "Message 2"]
messageQuery (Id index) = messages !! index

That might not seem like a big deal, but you either have to do that type conversion back and forth everywhere, or set up a boundary layer in your code where everything above is Int -> String then you convert it to Id -> Message to pass to the layer below.  Say I wanted to add internationalization, or format it in all caps, or add logging context, or whatever.  Those operations are all dead simple to compose with an Int -> String, and annoying with an Id -> Message.  It's not that there are never cases where the increased type restrictions are desirable, but the annoyance had better be worth the trade off.

You can use a type synonym instead of a wrapper (in Haskell type instead of newtype), which is much more common and doesn't require the conversions all over the place, but it doesn't provide the static type guarantees either like your OOP version, just a bit of enapsulation.  Type wrappers are mostly used where the client isn't expected to manipulate the value at all, just store it and pass it back.  For example, a file handle.

Nothing can prevent a client from being "subversive."  You're just creating hoops to jump through, for every single client.  A simple mock for a common unit test often requires weird behavior that doesn't make sense in production.  Your interfaces should be written so they don't care, if at all possible.


问:
How does the Hip hop virtual machine (HHVM) theoretically improve PHP runtime performance?
From a high level, how does Facebook, et. al use to improve PHP performance with the Hip Hop Virtual Machine?

How does it differ from executing code using the traditional zend engine? Is it because types are optionally defined with hack which allow for pre-optimization techniques?

My curiousity arose after reading this article, HHVM adoption.

答:
In short: they try to minimize random memory access and jumps between pieces of code in memory to play nicely with CPU cache.

According to HHVM Performance Status they optimized most frequently used data types, which are strings and arrays, to minimize random memory access. The idea is to keep data pieces used together (like items in an array) as close to each other as possible in memory, ideally in a linear fashion. That way, if data fits into CPU L2/L3 cache, it can be processed orders of magnitude faster than if it was in RAM.

Another technique mentioned is compiling most frequently used paths in a code in such a way that compiled version is as linear (e.i. has least amount of "jumps") as possible and loads data in/out of memory as rarely as possible.


问:
What's the point of implementing a Stack using two queues?
I have the following homework question:

Implement the stack methods push(x) and pop() using two queues.

This seems odd to me because:

A Stack is a (LIFO) queue

I don't see why you would need two queues to implement it

I searched around:

GeeksForGeeks

StackOverflow

and found a couple solutions. This is what I ended up with:

```<code>public class Stack<T> {
    LinkedList<T> q1 = new LinkedList<T>();
    LinkedList<T> q2 = new LinkedList<T>();

    public void push(T t) {
        q1.addFirst(t);
    }

    public T pop() {
        if (q1.isEmpty()) {
            throw new RuntimeException(
                "Can't pop from an empty stack!");
        }

        while(q1.size() > 1) {
            q2.addFirst( q1.removeLast() );
        }

        T popped = q1.pop();

        LinkedList<T> tempQ = q1;
        q1 = q2;
        q2 = tempQ;

        return popped;
    }
}
</code>```

But I don't understand what the advantage is over using a single queue; the two queue version seems pointlessly complicated.

Say we choose for pushes to be the more efficient of the 2 (as I did above), push would remain the same, and pop would simply require iterating to the last element, and returning it. In both cases, the push would be O(1), and the pop would be O(n); but the single queue version would be drastically simpler. It should only require a single for loop.

Am I missing something? Any insight here would be appreciated.

答:
There is no advantage: this is a purely academic exercise.

A very long time ago when I was a freshman in college I had a similar exercise1. The goal was to teach students how to use object-oriented programming to implement algorithms instead of writing iterative solutions using for loops with loop counters. Instead, combine and reuse existing data structures to achieve your goals.

You will never use this code in the Real WorldTM. What you need to take away from this exercise is how to "think outside the box" and reuse code.

Please note that you should be using the java.util.Queue interface in your code instead of using the implementation directly:

```<code>Queue<T> q1 = new LinkedList<T>();
Queue<T> q2 = new LinkedList<T>();
</code>```

This allows you to use other Queue implementations if desired, as well as hiding2 methods that are on LinkedList that might get around the spirit of the Queue interface. This includes get(int) and pop() (while your code compiles, there is a logic error in there given the constraints of your assignment. Declaring your variables as Queue instead of LinkedList will reveal it). Related reading: Understanding “programming to an interface” and Why are interfaces useful?

1 I still remember: the exercise was to reverse a Stack using only methods on the Stack interface and no utility methods in java.util.Collections or other "static only" utility classes. The correct solution involves using other data structures as temporary holding objects: you have to know the different data structures, their properties, and how to combine them to do it. Stumped most of my CS101 class who had never programmed before.

2 The methods are still there, but you cannot access them without type casts or reflection. So it is not easy to use those non-queue methods.

Body:
There is no advantage: this is a purely academic exercise.

A very long time ago when I was a freshman in college I had a similar exercise1. The goal was to teach students how to use object-oriented programming to implement algorithms instead of writing iterative solutions using for loops with loop counters. Instead, combine and reuse existing data structures to achieve your goals.

You will never use this code in the Real WorldTM. What you need to take away from this exercise is how to "think outside the box" and reuse code.

Please note that you should be using the java.util.Queue interface in your code instead of using the implementation directly:

Queue<T> q1 = new LinkedList<T>();
Queue<T> q2 = new LinkedList<T>();

This allows you to use other Queue implementations if desired, as well as hiding2 methods that are on LinkedList that might get around the spirit of the Queue interface. This includes get(int) and pop() (while your code compiles, there is a logic error in there given the constraints of your assignment. Declaring your variables as Queue instead of LinkedList will reveal it). Related reading: Understanding “programming to an interface” and Why are interfaces useful?

1 I still remember: the exercise was to reverse a Stack using only methods on the Stack interface and no utility methods in java.util.Collections or other "static only" utility classes. The correct solution involves using other data structures as temporary holding objects: you have to know the different data structures, their properties, and how to combine them to do it. Stumped most of my CS101 class who had never programmed before.

2 The methods are still there, but you cannot access them without type casts or reflection. So it is not easy to use those non-queue methods.


答: The exercise is needlessly contrived from a practical standpoint. The point is to force you to use the interface of the queue in a clever way to implement the stack. For example, your "One queue" solution requires that you iterate over the queue to get the last input value for stack "pop" operation. However, a queue data structure does not allow to iterate over the values, you are restricted to access them in the first-in, first-out (FIFO).

Title: What's the point of implementing a Stack using two queues?

Body:
I have the following homework question:

Implement the stack methods push(x) and pop() using two queues.

This seems odd to me because:

A Stack is a (LIFO) queue

I don't see why you would need two queues to implement it

I searched around:

GeeksForGeeks

StackOverflow

and found a couple solutions. This is what I ended up with:

```<code>public class Stack<T> {
    LinkedList<T> q1 = new LinkedList<T>();
    LinkedList<T> q2 = new LinkedList<T>();

    public void push(T t) {
        q1.addFirst(t);
    }

    public T pop() {
        if (q1.isEmpty()) {
            throw new RuntimeException(
                "Can't pop from an empty stack!");
        }

        while(q1.size() > 1) {
            q2.addFirst( q1.removeLast() );
        }

        T popped = q1.pop();

        LinkedList<T> tempQ = q1;
        q1 = q2;
        q2 = tempQ;

        return popped;
    }
}
</code>```

But I don't understand what the advantage is over using a single queue; the two queue version seems pointlessly complicated.

Say we choose for pushes to be the more efficient of the 2 (as I did above), push would remain the same, and pop would simply require iterating to the last element, and returning it. In both cases, the push would be O(1), and the pop would be O(n); but the single queue version would be drastically simpler. It should only require a single for loop.

Am I missing something? Any insight here would be appreciated.


答:
There is no advantage. You have correctly realized that using Queues to implement a Stack leads to horrible time complexity. No (competent) programmer would ever do something like this in “real life”.

But it's possible. You can use one abstraction to implement another, and vice versa. A Stack can be implemented in terms of two Queues, and likewise you could implement a Queue in terms of two stacks. The advantage of this exercise is:

you recap Stacks

you recap Queues

you get accustomed to algorithmic thinking

you learn stack-related algorithms

you get to think about tradeoffs in algorithms

by realizing the equivalence of Queues and Stacks, you connect various topics of your course

you gain practical programming experience

Actually, this is a great exercise. I should do it myself right now :)


问:
Where to create a file in WPF/MVVM
I'm building a WPF/MVVM application that takes input from the user and generates an output document which it saves in a temporary folder and opens for display in the native application (e.g. MS Word).  The document's data is, of course, represented by the model as well as the logic for constructing the actual document (including the interaction with a third-party library that works with document file formats).

My question is: should the actual file save-to-disk operation be in the model?  Or should it pass some kind of object (stream, possibly) back to the view model so it can be saved to disk there.  Where does something like that belong?

答: The Model is meant to represent both the current state of the data and the data access layer that represents the content. So, if you were using a database, you would handle read/write calls there. In that same vein, you should do disk reads and writes in your model (or, at least I would).</p>

Title: Where to create a file in WPF/MVVM


问:
What is the difference between function() and function(void)?
I have heard that it is a good practice to write functions that do not receive anything as a parameter like this:

```<code>int func(void);
</code>```

But I hear that the right way to express that is like this:

```<code>int func();
</code>```

What is the difference between these two function declarations in both C and C++?

答:
C and C++ are different in this respect.

C 2011 Online Standard

6.7.6.3 Function declarators (including prototypes)

...

10 The special case of an unnamed parameter of type void as the only item in the list
specifies that the function has no parameters.

...

14 An identifier list declares only the identifiers of the parameters of the function. An empty
list in a function declarator that is part of a definition of that function specifies that the
function has no parameters. The empty list in a function declarator that is not part of a
definition of that function specifies that no information about the number or types of the
parameters is supplied.145)

In short, an empty parameter list in a function declaration indicates that the function takes an unspecified number of parameters, while an empty parameter list in a function definition indicates that the function takes no parameters.

```<code>T foo( void ); // declaration, foo takes no parameters
T bar();       // declaration, bar takes an *unspecified* number of parameters

T foo( void ) { ... } // definition, foo takes no parameters
T bar() { ... }       // definition, bar takes no parameters
</code>```

As far as C is concerned, you should never use an empty identifier list in a function declaration or definition.  If a function is not meant to take any parameters, specify that by using void in the parameter list.

Online C++ standard

8.3.5 Functions [dcl.fct]

...

4 The parameter-declaration-clause determines the arguments that can be specified, and their processing, when
the function is called. [ Note: the parameter-declaration-clause is used to convert the arguments specified
on the function call; see 5.2.2. — end note ] If the parameter-declaration-clause is empty, the function takes
no arguments. A parameter list consisting of a single unnamed parameter of non-dependent type void is
equivalent to an empty parameter list. Except for this special case, a parameter shall not have type cv void.
If the parameter-declaration-clause terminates with an ellipsis or a function parameter pack (14.5.3), the
number of arguments shall be equal to or greater than the number of parameters that do not have a default
argument and are not function parameter packs. Where syntactically correct and where “...” is not part of
an abstract-declarator, “, ...” is synonymous with “...”. [Example: the declaration```<code>    int printf(const char*, ...);
</code>```declares a function that can be called with varying numbers and types of arguments.```<code>    printf("hello world");
    printf("a=%d b=%d", a, b);</code>```
However, the first argument must be of a type that can be converted to a const char* — end example ]
[ Note: The standard header <cstdarg> contains a mechanism for accessing arguments passed using the
ellipsis (see 5.2.2 and 18.10). — end note ]

In the case of C++, an empty parameter list in either a declaration or a definition indicates that the function takes no arguments, and is equivalent to using a parameter list of void.

Body:
C and C++ are different in this respect.

C 2011 Online Standard

6.7.6.3 Function declarators (including prototypes)

...

10 The special case of an unnamed parameter of type void as the only item in the list
specifies that the function has no parameters.

...

14 An identifier list declares only the identifiers of the parameters of the function. An empty
list in a function declarator that is part of a definition of that function specifies that the
function has no parameters. The empty list in a function declarator that is not part of a
definition of that function specifies that no information about the number or types of the
parameters is supplied.145)

In short, an empty parameter list in a function declaration indicates that the function takes an unspecified number of parameters, while an empty parameter list in a function definition indicates that the function takes no parameters.

T foo( void ); // declaration, foo takes no parameters
T bar();       // declaration, bar takes an *unspecified* number of parameters

T foo( void ) { ... } // definition, foo takes no parameters
T bar() { ... }       // definition, bar takes no parameters

As far as C is concerned, you should never use an empty identifier list in a function declaration or definition.  If a function is not meant to take any parameters, specify that by using void in the parameter list.

Online C++ standard

8.3.5 Functions [dcl.fct]

...

4 The parameter-declaration-clause determines the arguments that can be specified, and their processing, when
the function is called. [ Note: the parameter-declaration-clause is used to convert the arguments specified
on the function call; see 5.2.2. — end note ] If the parameter-declaration-clause is empty, the function takes
no arguments. A parameter list consisting of a single unnamed parameter of non-dependent type void is
equivalent to an empty parameter list. Except for this special case, a parameter shall not have type cv void.
If the parameter-declaration-clause terminates with an ellipsis or a function parameter pack (14.5.3), the
number of arguments shall be equal to or greater than the number of parameters that do not have a default
argument and are not function parameter packs. Where syntactically correct and where “...” is not part of
an abstract-declarator, “, ...” is synonymous with “...”. [Example: the declaration
    int printf(const char*, ...);

declares a function that can be called with varying numbers and types of arguments.
    printf("hello world");
    printf("a=%d b=%d", a, b);

However, the first argument must be of a type that can be converted to a const char* — end example ]
[ Note: The standard header <cstdarg> contains a mechanism for accessing arguments passed using the
ellipsis (see 5.2.2 and 18.10). — end note ]

In the case of C++, an empty parameter list in either a declaration or a definition indicates that the function takes no arguments, and is equivalent to using a parameter list of void.


问:
The need for source control software - Team Foundation Server? or something different?
Recently,

Here at the company, more than one programmer was appointed in charge for a LightSwitch(C#) software development project and immediately there was a need of some sort of source control/sync.

We have never used Team Foundation Server but we'd gladly use it if it's worth it.

Is it the right tool to use for
synchronising code between
programmers?

Does it have the needed features?

Do you have any other tool in
mind? (I have used TortoiseSVN but
it was too simple and 'texty' if you
know what I mean, we need a
professional tool)

What other features does Team
Foundation has that we can use?

(if you did not understand any of the above please ask me to clarify further)

答:
To add to the points everyone else has been making, don't forget that there are perfectly good Distributed Version Control Systems (DCVS) that work very well. I personally prefer Mercurial as a .NET developer, but there is an equally strong case for Git as well.

There is a really good answer here on the advantages of a DCVS over a traditional CVS system like TFS or SVN.


问:
How to handle pull requests to original repo with changes dependent on a newer version of the compiler
I have a github project that I've forked. The original repo was written for a version of OCaml before version 4.02.1.  The 4.02.1 compiler gives me various deprecation warnings which I plan on fixing and committing to my repo.  I'm not sure if I should push my changes back to the original project.

My question is: in a situation where code from a third-party (me) requires a newer version of a library or compiler than the original author/project is using, how should I handle sharing my code with the original repo?  It seems inconsiderate to just offer the new code without some kind of explanation and I certainly don't want to break the build on the original repo.

How is this kind of situation handled?

答:
I'll describe how this is typically handled in github. However all of that is just code, so it is relevant elsewhere.

Really spiffy projects like the ones I run, have tests to make sure everything is working okay.

Furthermore, the way cool projects like the ones I work with have some sort of continuous integration. That just means there is a way for some external independent system to run the tests on its own. github arranges a project to used a canned set of git commit hooks which will tell the independent system that a change has been commited.

Usually there are instructions that you can provide to the continuous integration system that help it build the system. Specifically these instructions or configuration might specify what version(s) of OCaml to test with.

With all of this in place, when you submit a "pull request", github runs the git hook which kicks off the continous integration system which then makes available the status of the check. Github will then notice it (because the hook was canned and custom for a ci so it knows where to look). And then it will alert the potential owner whether it is safe to merge the code or not. Even without continuous integration github will do a merge off to the side just to make sure there are no merge conflicts.

Ok. But let's suppose you are working with less sophisticated projects. Since this is git, that's cool too, it can help you on its own.

Here what you could do then is make a branch and restrict your changes to that branch. Then request a pull from that branch. The owner will probably merge your changes into a similarly-named branch and then try it out. If things work okay, then that person will merge the branch into the "main" branch.

And in fact whether you are using github and the fancy stuff or not, it is always good to work in a branch for your changes off of another project. See also git flow


答:
It's really no different than any other change.  If it's a significant amount of work, run it by the mailing list first.  Someone may already be working on it.  If it's a trivial amount of work, just do it and submit a pull request with a clear explanation.  The worst that will happen is it will get rejected.

Deprecation is done for different reasons, and often your changes can be made backward-compatible to older language versions.  Try to do so if you can.  For example, ISO-latin1 characters in identifiers were added to deprecation warnings in 4.02.  You can certainly compile identifiers without ISO-latin1 characters in older versions.

Title: How to handle pull requests to original repo with changes dependent on a newer version of the compiler

Body:
I have a github project that I've forked. The original repo was written for a version of OCaml before version 4.02.1.  The 4.02.1 compiler gives me various deprecation warnings which I plan on fixing and committing to my repo.  I'm not sure if I should push my changes back to the original project.

My question is: in a situation where code from a third-party (me) requires a newer version of a library or compiler than the original author/project is using, how should I handle sharing my code with the original repo?  It seems inconsiderate to just offer the new code without some kind of explanation and I certainly don't want to break the build on the original repo.

How is this kind of situation handled?


答:
As others already noted: there is no real-world advantage.

Anyway, one answer to the second part of your question, why not simply to use one queue, is beyond the Java.

In Java even the Queue interface has a size() method and all the standard implementations of that method are O(1).

That is not necessarily true for the naive/canonical linked list as a C/C++ programmer would implement, which would just keep pointers to the first and last element and each element a pointer to the next element.

In that case size() is O(n) and should be avoided in loops. Or the implementation is opaque and only provides the bare minimum add() and remove().

With such an implementation you'd have to count the number of elements first by transfering them into the second queue, transfer n-1 elements back to the first queue and return the remaining element.

That said, it would probably not make up something like this if you live in Java-land.


答: Personally, if I think some code need not exist, I comment it out, then run the program to make sure it didn't make anything glitch.  If everything is fine, I delete the commented-out code.</p>

Title: Code cleanup methods and/or code coverage tools

Body:
I have an application at work, which I started work on about 7 years ago. This was my first engagement in ASP.NET web applications, and coming from a Win32 background I had a hard time adjusting.

All this time, both the project and myself have "matured" and now most parts of it are well defined, properly structured and readable. However, there is a significant piece of it, that is "old junk". By that I mean old obsolete code, that was not working well, or was not properly structured, which has been replaced, but left in the source files instead of being removed. I must note here, that I was not the sole developer, but did most of the coding throughout.

What I want to do, is whenever I have free time at work, to remove the old obsolete and unused code. Are there any techniques/methodologies that I can use/follow in order to do this more efficiently? Any tools perhaps?

EDIT: (clarification based on feedback)
The code I am talking about is not used anywhere, and is not called from anywhere in the project. What I need is way to find out where the code resides, since we are talking about a large codebase. So something in terms of code coverage tools would help. Any suggestions for asp.net projects? (the particular case is in Web Site project form)


答:
There is definitely a real purpose for making a queue out of two stacks.  If you use immutable data structures from a functional language, you can push into a stack of pushable items, and pull from a list of poppable items.  The poppable items gets created when all items have been popped out, and the new poppable stack is the reverse of the pushable stack, where the new pushable stack is now empty.  It's efficient.

As for a stack made of two queues?  That might make sense in a context where you have a bunch of large and fast queues available.  It's definitely useless as this sort of Java exercise.  But it might make sense if those are channels or messaging queues.  (ie: N messages enqueued, with an O(1) operation to move (N-1) items at the front into a new queue.)


问:
Is there something peculiar to Matlab or Mathworks that supports so much "undocumented" code?
I've been drilling into a lot of Matlab recently trying to interface with an in house algorithm engineer's work to modularize it for use in a test bench outside his suite of applications. I've come across several links from several different areas and concepts that connect to this undocumented MATLAB website.

I've been hesitant to dive into any solutions proposed there since I've always been taught not to rely upon undocumented behavior, since well it may be deprecated and is generally subject to change. I suppose however for the sort of software that would be developed in MATLAB such implementation shake ups wouldn't bring too large of a house crumbling down to be refurbished, but I was curious is there something to the way Mathworks develops that they manage to allow so many hooks into their undocumented architectures and frameworks? What could be preventing them from formalizing these things.

Just as a concrete example while researching UI layout techniques for programmatic GUI creation one of their articles made mention of this uiflowcontainer, which if you get the documentation on it you find it is undocumented.

```<code>>> help uiflowcontainer
  This function is undocumented and will change in a future release
</code>```

In general I find it very curious and amusing that such a development tool has built such a following to its undocumented internals. Any thoughts on that reality? Is it foolish, crafty, or something in between?

答:
Neither foolish nor crafty I believe: MATLAB software is used for very serious engineering, science, finance, and many other fields. This being the case, MathWorks (the company that develops Matlab) are very careful not to publicly document things that they are not 100% certain will remain as-is in future Matlab versions. There are numerous examples of such functions and features/functionality, and uiflowcontainer is just one of them. In the vast majority of cases, these undocumented features/functions have remained unchanged for many years, 10-15 years or more. In some cases (e.g., uitable in R2008a or uitab in R2014b) they eventually become fully documented/supported, and in other cases they remain undocumented. In rare cases they are significantly modified at some point in time.

The bottom line is that using such features/functions can significantly improve your existing Matlab code and will probably not require any major rework in the near future. However, the down-side is that a rework might indeed be necessary at some future time if you upgrade to a new Matlab release that changes the undocumented behavior. So is it worth the risk? The answer to this depends on the specific feature and its usage in your work: the benefit it gives you today vs. the risk of needing to recode it tomorrow.

p.s. – I and my website (http://UndocumentedMatlab.com) are entirely independent and not affiliated with MathWorks in any way. All the undocumented things that I publish in my website and books are entirely due to self-made discoveries, and were not provided to me by MathWorks. In fact, MathWorks are extremely careful not to divulge to me any undocumented things. They do not support or promote my undocumented work in any way.


问:
When is a event listener invoked during program execution?
I am using the Obervable-Observer Pattern.

```<code>MyClass extends Observable{

  invokeListeners(){
     doSomething;
     setChanged();
     notifyListeners();//This invokes onUpdate() in "implements Observer"

     return value;
  }
}

ClassTwo implements Observer{

   onUpdate(){
      //This is called after notifyListeners();
   }
}
</code>```

My question is when will the onUpdate method in the Listener Class get invoked? After the invokeListeners() methods completes, or right after notifyListeners()?

答:
To check the stacktrace, I incremented a static int in the update() method of all the listeners.

I added a System.out.println() in the method where I call notifyListeners() and in the update() methods of the listeners to see the value of the static. Following is stacktrace values -

public static int observer = 0; //Initialized

StackTrace :
After NotifyListeners : 0
In update() : 1
In update() : 2
In update() : 3

This implies that the method in which notifyListeners() call is placed, first completes its execution and after that the update() methods in the Observer are called in a loop.


问:
What does pi mean in this BFS algorithm pseudocode?
I have the following pseudocode for breadth-first search algorithm

BFS(G,s)
 1 for each vertex u ∈ V(G) \ {s}
 2     color[u] = white
 3     d[u] = ∞
 4     π[u] = nil
 5 color[s] = gray
 6 d[s] = 0
 7 π[s] = nil
 8 Q = ∅
 9 Enqueue(Q,s)
10 while q ≠ ∅
11     u = Dequeue(Q)
12     for each v ∈ Adj[u]
13         if color[v] == white
14             color[v] = gray
15             d[v] = d[u] + 1
16             π[v] = u
17             Enqueue(Q,v)
18     color[u] = black
```

Original image

I do not understand what the letter π indicates in this context. I am not familiar with this algorithm and it is a difficult to guess.

I think d indicates the distance, color is of course the color, but that π... it appears to be a variable of some sort but I do not understand its function in this pseudocode.

答: I believe the use of π here is actual “parent of”. So in this case, the “parent” of v  is u because we're looking at all nodes adjacent to u. This verbiage can be found here (PDF link).

ContentLicense: CC BY-SA 4.0


问:
Algorithm to find groups of common relations
I have a very large dataset with two columns of interest: Name and Cousin.

Each row has a unique name and each name has a cousin.

The data is mutually inclusive, so the cousin's name will also appear as another row in the data.

The effect is therefore a big dataset with lots of names of people who are related to each other.

The relations, however, form themselves into separate groups. These are groups that have no relation with any person in any other group.

E.g (using -> to denote a relation)

A->C->E->G = Group 1

B->D->F->H = Group 2

None of the people in Group 1 shares a relation with any person in Group 2.

So, I'm looking for an approach to find these groups of related people using only their names and relations. This could be some pseudo-code or a conceptual approach, anything to point me down the right path.

Example dataset:

```<code>Name Cousin
A    C
B    D
C    E
D    F
E    G
F    H
G    E
H    K
I    M
K    H
M    I
</code>```

This data would be aggregated into three groups: Group 1 (A,C,E,G); Group 2 (B,D,F,H,K); Group 3 (I,M).

答:
You are building a set of graphs.

You start out and start walking the list of relationships you have gotten back.

A -> C

So, lets make a graph that represents that.

```<code>A - C
</code>```

And then you've got:

B -> D

Neither B nor D are represented in any of the graphs currently.  So now you have:

```<code>A - C

B - D
</code>```

And then C -> E, so we hunt up C and link to to E.  Now we've got:

```<code>A - C - E

B - D
</code>```

And so on.  That will give you the give you all of the related graphs.

"Fine," you say, "but that doesn't really get any closer to doing an implementation"

The real problem here is how to represent the graphs.

Lets write some pseudocode. I speak a perlish dialect - but its not perl.

$nextGroup = 1
for each ($key, $link) in (@row) {
    if(not defined $group{$key}) {
        $group{$key} = $nextGroup++;
    }
    if(not defined $group{$link} || $group{$link} == $group{$key}) {
        $group{$link} = $group{$key}
    } else {
        for each ($k, $v) in (entries %group) {
            if($v == $group{$link}) {
                $group{$k} = $group{$key};
            }
        }
    }
}
```

<p>What is it doing?  It iterates over each row returned. If the key isn't a known item, it assigns it to a new group. It then assigns the group the key belongs to to the link.  If the link already has a <em>different</em> value, then it finds all the links with the same value as it and assigns them to the value of the key.</p>

<p>So, we start out again.</p>

```A = 1 (nextGroup = 2)
  C = 1
B = 2 (nextGroup = 3)
  D = 2
C is 1
  E = 1
D = 3 (nextGroup = 4)
  F = 3
E is 1
  G = 1
...
```

At the end of this, the groups map/dictionary/hash (whatever your language calls it) is going to have each individual in there with a corresponding value.  All entries with the same value belong to the same graph being depicted.

Body:
You are building a set of graphs.

You start out and start walking the list of relationships you have gotten back.

A -> C

So, lets make a graph that represents that.

A - C

And then you've got:

B -> D

Neither B nor D are represented in any of the graphs currently.  So now you have:

A - C

B - D

And then C -> E, so we hunt up C and link to to E.  Now we've got:

A - C - E

B - D

And so on.  That will give you the give you all of the related graphs.

"Fine," you say, "but that doesn't really get any closer to doing an implementation"

The real problem here is how to represent the graphs.

Lets write some pseudocode. I speak a perlish dialect - but its not perl.

$nextGroup = 1
for each ($key, $link) in (@row) {
    if(not defined $group{$key}) {
        $group{$key} = $nextGroup++;
    }
    if(not defined $group{$link} || $group{$link} == $group{$key}) {
        $group{$link} = $group{$key}
    } else {
        for each ($k, $v) in (entries %group) {
            if($v == $group{$link}) {
                $group{$k} = $group{$key};
            }
        }
    }
}

What is it doing?  It iterates over each row returned. If the key isn't a known item, it assigns it to a new group. It then assigns the group the key belongs to to the link.  If the link already has a different value, then it finds all the links with the same value as it and assigns them to the value of the key.

So, we start out again.

A = 1 (nextGroup = 2)
  C = 1
B = 2 (nextGroup = 3)
  D = 2
C is 1
  E = 1
D = 3 (nextGroup = 4)
  F = 3
E is 1
  G = 1
...

At the end of this, the groups map/dictionary/hash (whatever your language calls it) is going to have each individual in there with a corresponding value.  All entries with the same value belong to the same graph being depicted.


问:
The correct way to use Sessions (PHP)?
I am making a website that requires logins, and would like to know what a good approach is.
Right now, I am thinking of the following:

User sends username and password to server, where it is validated.

If its valid, then session_start(); is called, and session_id() is stored in my database, which will be used as an access token for the rest of data fetching.

If user logs out, that session_id() will be destroyed in the database.

I would like to know how to delete the session_ids() , if the user DIDNT log out, and just closed the browser.

I would like to know how popular websites like facebook handle sessions.

答:
You're in the right neighborhood.

Most PHP applications will have active sessions for all page views, regardless of whether a user is logged in.  It would essentially do a session start() at the beginning of the script, and a save() at the end.  That session would exist for the entire visit to the site, or longer, depending on how you have PHP set to expire cookies.

When a user submits a login form and successfully logs in, you can then store the user information as a session variable.  For example, at the most basic, you can store the user id associated with the session:

```<code>$_SESSION['user_id'] = 1234;
</code>```

When the session is saved, that value is stored with the session.  Session variables are not sent to the client - they are stored on the web server (where exactly it is stored is configurable, but ideally in a database).

Now, on the next page load, you can check the value of $_SESSION['user_id'] to get the user id of the logged in user, if any.  This is because when the session loads at the top of the script, it has access to the session variables you assigned on other pages in that session.

When a user logs out, you set the $_SESSION['user_id'] back to 0.  On the next page load, the user is no longer associated with that session.

If you want the user to get logged out when the browser is closed, you need to set the cookie lifetime to 0.  If you want the session to persist, you want to set the cookie lifetime to the maximum number of seconds you want the session to exist (for example, 60 * 60 * 24 * 30 would be 30 days).

This is just a conceptual overview.  There's some security issues involved with sessions, so make sure you learn about them as well before you make a site live.

Title: The correct way to use Sessions (PHP)?

Body:
You're in the right neighborhood.

Most PHP applications will have active sessions for all page views, regardless of whether a user is logged in.  It would essentially do a session start() at the beginning of the script, and a save() at the end.  That session would exist for the entire visit to the site, or longer, depending on how you have PHP set to expire cookies.

When a user submits a login form and successfully logs in, you can then store the user information as a session variable.  For example, at the most basic, you can store the user id associated with the session:

$_SESSION['user_id'] = 1234;

When the session is saved, that value is stored with the session.  Session variables are not sent to the client - they are stored on the web server (where exactly it is stored is configurable, but ideally in a database).

Now, on the next page load, you can check the value of $_SESSION['user_id'] to get the user id of the logged in user, if any.  This is because when the session loads at the top of the script, it has access to the session variables you assigned on other pages in that session.

When a user logs out, you set the $_SESSION['user_id'] back to 0.  On the next page load, the user is no longer associated with that session.

If you want the user to get logged out when the browser is closed, you need to set the cookie lifetime to 0.  If you want the session to persist, you want to set the cookie lifetime to the maximum number of seconds you want the session to exist (for example, 60 * 60 * 24 * 30 would be 30 days).

This is just a conceptual overview.  There's some security issues involved with sessions, so make sure you learn about them as well before you make a site live.


问:
Why do people do REST API's instead of DBAL's?
At the past two companies, I've been at, REST API's exist for querying data via webapp - i.e. instead of having the webapp do SQL directly it calls a REST API and that does the SQL and returns the result.

My question is - why is this done?

If it was going to be exposed to third-parties I could understand. Better to expose a limited REST API than the full DB. But in both of these companies that's not the the case.

It's been suggested to me that these REST API's make it easier to switch between DBMS. But isn't that the point of a database abstraction layer (DBAL)? Maybe you use an ORM  as your DBAL or maybe you could just write raw SQL and have your DBAL translate the DB specific stuff if appropriate (e.g. translate LIMIT for MySQL to TOP for MSSQL).

Either way it seems unnecessary to me. And I think it makes diagnosing issues more difficult as well. If a report on the webapp is giving the wrong numbers you can't just dump out the SQL query - you have to dump the REST URL and then go into the project that's serving as the REST API and pull out the SQL from that. So it's an extra layer of indirection that slows down the diagnostic process.

答:
You are right, there is no clear benefit to introduce a REST API layer between a web app and a database, and it has a cost in complexity and performance overhead.

The reason you are getting contradictory answers is confusion about what is the 'client' in your architecture.

In your architecture (if I understand it correct), you have browsers interacting with a single web app, which in turn is interacting with the database. Introducing a REST API layer between the web app and the database has no benefit. All the stated benefits (caching, isolation of database etc) can be achieved with data access layer(s) in code.

But there are some other architectures where a REST API makes sense:

If you have multiple clients accessing the database - that is, not a single web app but multiple independent web apps accessing the same database. It may have benefit to create a common REST interface to allow sharing of data model, caching etc. Sure you can get some of the benefit by sharing the same DAL libraries, but that wont work if the apps are developed in different languages and on different platforms. This is common in enterprise systems.

If you have multiple desktop apps accessing the database directly. This is the classic "two-tier" architecture, which have fallen out of favor compared to web apps. Introducing a REST layer allows you to centralize data access logic and especially it allows tighter control of security, since it is risky to have multiple distributed clients accessing the same database directly.

If you have JavaScript code which directly fetches data from the server, then you need something like a REST API in any case.


问:
Why 'class String' definition has 'final' modifier?
This answer gives an indication that class String is declared final for thread safety, which does not convince.

This answer does not convince when it says: And so, you make the classes final. There can be no mutable String, because its an immutable class and its final.

Because,

below field with final modifier,

```<code>/** The value is used for character storage. */
    private final char value[];
</code>```

in class String would suffice/indicate that data stored in the created object is suppose to be immutable and thread safe.

So, class String being final has nothing to do with immutability or thread safety.

But it is not clear, why class String is declared final?

Because, as per below class definition, it has final modifier:

```<code>public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
{ .... }
</code>```

So, class String cannot be inherited.

Despite field value[] in class String is declared final, additionaly, What is the necessity for class String also to be final?

Note: Answers to this question will give an idea behind this design decision

答:
You answered your question in your question.

Class String cannot be inherited because it has a final modifier in the class definition. The final modifier does just that in a class definition, declares a class which cannot be inherited from, it has nothing to do with immutability in this case.

The rationale behind this is that a programmer may subclass String therefore have an object which "looks like" a String (i.e. can be passed to methods which take a String argument) however is mutable whereas String is expected to be immutable.


问:
Early subtasking at the beginning of each sprint
I have joined a new team which is using Agile/Scrum, and their development process is as follows:

1) developers review each story before each sprint to make sure it doesn't miss anything critical. There's a formal state for that in the workflow.

2) during the Sprint kickoff, the entire team does an estimation (poker planning) on how many story points each story would cost.

3) finally, immediately after each sprint starts, each developer is required to eagerly break down all of assigned stories into subtasks with time estimates (as opposed to subtasking before starting each story).

The main argument for the last step is that it helps to discover if implementing a story would take longer than anticipated and warn scrum master about potential risks of missing sprint deadlines.

Yet I find this counter-productive, mainly because of the following reasons:

if the aim is to provide rough estimate, story points (step #2) is what does the job. Otherwise why bother with story points at all? - just do subtasking early on.

if the aim is to provide accurate estimates, then this is a clear example of what is described in Human Task Switches Considered Harmful. This, I think, is especially the case for fresh developers who join existing teams in big projects where understanding what needs to be done can take up to 50% of the time. You are required to get into details of story #1, then story #2, #3, etc. etc. which yields a lot of information churn.

I am also being told that such practice is "by the book" and I'm not even meant to discuss this. Can anyone provide a reference to such practice - whether this is clearly defined in Scrum bibles, and/or perhaps provide any extra insight?

答:
This is not dissimilar to how we run some of our scrum process. We

Estimate stories near the top of the backlog in "story points"

Select/explain stories based on the story points that we think will "make up" the sprint

Break down the stories into more detailed technical tasks

Estimate the technical tasks and compare with the original story points estimate (we know approximately how much development time a story point normally equates to)

But what you want to know is why we estimate twice!

We do a coarse estimate (based on the story) because we like to be able to make predictions about what might be in the next sprint, and maybe even the one after that. Ultimately management have to be able to communicate with the customer about likely time-scales, so if we don't have this coarse scale estimation then long term planning is virtually impossible.

Obviously, this means we do coarse estimates for more than just the current sprint. Because there's no guarantee the backlog order won't change for the next sprint we don't want to invest the time in doing task breakdowns and fine-scale estimates until they're necessary.

We break down the task to make sure that all the tasks have been enumerated and that stories can be worked on in parallel more easily.

We do fine-scale estimates (based on the task) because this gives us a much smoother burn-down graph (particularly where there's no easy way to break a large story apart into viable "features").

Because we do both, they act as sanity checks on one another - a wild discrepancy indicates we need a mistake somewhere that we need to identify. This is a useful by-product, but not the reason in itself why we estimate "twice".

Rereading your question and comment, I see there are some differences between our workflow and yours.

We do breakdowns as a team, we find although the overhead is greater the technical discussion we get from this is often very valuable and can detect shortcomings in our story. When we have experience, knowledge or ability disparity this discussion is also where those with more can help out those with less (very useful with new hires).

We do estimates at the task level as a team, one of the reasons why "planning poker" works is because of the "wisdom of crowds" phenomenon - as I mention in comments, by this point estimating a task should take less than 30 seconds, so the overhead is negligible.

It sounds like the reason your team does task breakdowns and task estimates is for a smooth burn-down - which is fine, that's all part of monitoring the progress of the sprint and allowing your scrum-master to detect and resolve issues early. If you want this information you have to do the breakdowns and estimates and you have to do them first.

In my opinion task switching is not likely to be a problem for you here, I don't think that breaking down different tasks is really a task switch in the same sense that flipping from developing one feature to another part way through is a task switch. I think gaining an understanding of the overall "architecture" of the sprint is probably quite a useful thing.

However, I think there may be some other problems you could consider. As always with agile you should identify a problem you have and propose a solution,  then decide if your solution worked in the retrospective. This is the crux of building an agile solution that works for your company and your team. So, some problems you might have:

You're doing breakdowns individually - so how are your junior/inexperienced team members learning from your senior team members? Sure, they can probably learn everything themselves - but they'll learn faster if they're mentored. Are junior team members taking a long time to break things down? Are they making mistakes or missing things that cost the team time in the long run? Breaking down as a team can help here.

You're doing estimates individually - the same applies as the first point, but in addition are these estimates less accurate than they could be?

It sounds like tasks are assigned at the start of the sprint, but if this is the case then how expensive are you finding it when you have to change the assignment? If someone is falling behind or ill, how easy is it for someone else to pick-up their tasks? Do they have to go through the task breakdowns and try to understand them without interrupting the original assignee? If you breakdown and estimate as a team then everyone should be able to work on everything!

Are your stories too big? If the break down takes 50% of the time, the stories sound like they're very involved - perhaps they can be made smaller? We keep our stories within 1 man week of work.

Are your tasks too small? If you're spending a long time making task lists maybe you're going into too much detail? We tend to have tasks between 1 and 8 man hours worth of work so that over the course of a day everyone makes some progress to report at the next daily standup.


问:
What is faster? Using REST API or querying a database directly?
What is faster performance wise? Creating a REST API and having your web app use the REST API to do all interactions with your database OR querying your database directly (i.e. using whatever typical object your language uses to query a database such as JDBC for Java)?

The way I see it with REST:

You make an object in your code to call the REST method

Call http method

Code inside your REST API queries the database

Database returns some data

REST API code packs up the data into Json and sends it to your client

Client receives Json/XML response

Map response to an object in your code

On the other hand, querying a database directly:

You make an object with query string to query the database

Database returns some data

Map response to an object in your code

So wouldn't this mean that using a REST API would be slower? Maybe it depends on the type of database (SQL vs NoSQL)?

答:
Introducing an extra service tier always have a cost in complexity and performance overhead. There are some specific kinds of architecture where introducing a shared service tier (like a REST API) may improve perforce due to shared caching - but it sounds like it is not the kind of architecture you have.

Consider an architecture where you have multiple web apps or multiple desktop apps connecting directly to the same database. If they perform the same queries often, it may improve performance to cache query results in a shared service. Especially if you have say hundreds of desktop apps accessing the same database directly (not through a web app!) and performing the same queries, there could be a major improvement. However, even in this architecture, the primary reason to introducing a shared service would probably be security and data abstraction rather than performance.

But it sounds like you have a single web app which connects to the database directly. In that case there is no benefit to introduce an additional service layer. Caching, database abstraction etc. could be handled at the data access layer in the same application.


答:
TL;DR

Leakage of implementation detail due to MATLAB ".m" files being shipped in source code form.

Frequent changes of software requirements, features, and implementation detail.

Complexity due to many different underlying dependencies, all of which suffer from the phenomenons listed here.

Every complex software system (consisting of multiple architectures, layers, languages, and evolving a lot of generations over many decades) will have lots of implementation details.

The reason that the undocumented functionality in MATLAB is discoverable is because:

First, anything that Mathworks chooses to implement in its own MATLAB language will be shipped with the MATLAB application in source code form. This makes it possible for licensees to see its implementation detail. On the contrary, anything Mathworks chooses to implement in Java and C (MEX) will be shipped in compiled form.

However, this doesn't invalidate the general engineering advice that one should depend on the documented API, not on implementation details that could change from versions to versions. Just because something is possible (visible to you) doesn't mean it's a good idea (to use it).

Second, MATLAB prides itself on satisfying customer requests. Sometimes such requests require behavior changes. As a result, MATLAB has undergone many behavior changes.

Sometimes, some other customers will ask for the old behavior back. For this reason, switches are provided to make all customers happy.

Third, MATLAB uses a lot of existing technologies, such as the Java GUI. From versions to versions, the behavior of Java GUI also changes. Switches are needed to ensure compatibility with behavior changes inside Java GUI.

Title: Is there something peculiar to Matlab or Mathworks that supports so much "undocumented" code?

Body:
I've been drilling into a lot of Matlab recently trying to interface with an in house algorithm engineer's work to modularize it for use in a test bench outside his suite of applications. I've come across several links from several different areas and concepts that connect to this undocumented MATLAB website.

I've been hesitant to dive into any solutions proposed there since I've always been taught not to rely upon undocumented behavior, since well it may be deprecated and is generally subject to change. I suppose however for the sort of software that would be developed in MATLAB such implementation shake ups wouldn't bring too large of a house crumbling down to be refurbished, but I was curious is there something to the way Mathworks develops that they manage to allow so many hooks into their undocumented architectures and frameworks? What could be preventing them from formalizing these things.

Just as a concrete example while researching UI layout techniques for programmatic GUI creation one of their articles made mention of this uiflowcontainer, which if you get the documentation on it you find it is undocumented.

```<code>>> help uiflowcontainer
  This function is undocumented and will change in a future release
</code>```

In general I find it very curious and amusing that such a development tool has built such a following to its undocumented internals. Any thoughts on that reality? Is it foolish, crafty, or something in between?


问:
How can I write unit tests that simplify feature implementation?
I'm a newbie to working in software development and I read a lot about how cool unit tests are. Now, I've made my first steps into a project where I'm working with a number of equally unexperienced programmers which is why we have produced a bit of spaghetti code. I'm trying to learn how to use testing and other techniques to improve the code quality but one of my newbie co-workers says that tests make things more difficult. Apparently, he has done internships in teams where unit tests were used.

He argued that tests were constantly in his way when he tried to implement a new feature. The tests would fail after he had changed the code. So he had to adapt the tests which of course increased his workload.

But that doesn't make sense to me. I thought tests were supposed to make things easier. So, I suspect that he either didn't implement the features correctly or that the unit tests were badly done. So, I'm wondering: How can I write unit tests so that they don't fail just because a new feature was implemented?

答:
By making them test just the thing they're about, and not lots of unrelated properties that are true now but might change later.

Some examples from my experience. Often systems are supposed to send notifications to their users when certain things happen. With a proper test harness, it's easy to mock email messages and verify that they go out, get to the correct recipient and say what they're supposed to say. However, it's not a good idea to assert simply "When this even happens, this user receives that exact message text". Such a test would fail whenever the I18N texts are revised. It's much better to assert "The message contains the user's new password / The link to the announced resource / the user's name and a greeting", so that the test keeps working and only breaks when the routine does, in fact, not do its stated job.

Similarly, when you test auto-generated IDs for something, never assume that whatever value is generated at the moment will always be generated. Even when your test harness doesn't change, the implementation of that feature might change so that the outcome changes while still fulfilling its contract. Again, you don't want to assert "The first user receives ID AAA", but rather "The first user receives an ID composed of letters, and the second user receives an ID also composed of letters and distinct from the first one".

In general, beware of testing things that aren't in the contract for the thing you're testing. Understanding what is essentially true about the behaviour of a unit and what is only accidentally true is the key to writing minimal covering tests - and it is also extremely helpful for understanding the system and maintaining it successfully. This is one way in which test-driven development improves outcomes even when not catching bugs.


问:
Is the git "Golden Rule of Rebasing" so essential?
I had a discussion recently with people absolutely opposed to a rebase strategy of feature branches on GIT. It seems to be an accepted pattern to use rebase only for local, private branches but never use it when there's several people working on a same feature & branch, as per this so-called "Golden Rule of Rebasing" (like explained here: https://www.atlassian.com/git/tutorials/merging-vs-rebasing/conceptual-overview )

I am just surprised there's a consensus on this. I worked 3 years with a full rebasing strategy, with about 20 developers working togeteher and guess what, it worked.

The process is basically:

You create your feature branch, let's call it "myfeature", and push it to origin/myfeature

Other people may check it out and work on it

You may sometimes rebase it from master: from "myfeature", git rebase origin/master ; and then, yes, you have to push-force it.

What happens when other people want to push their commits? They just rebase it: git rebase origin/myfeature . So they're now in fast-forward and can push it without forcing.

The only principle to respect is that the feature branch is owned by someone. The owner is the only one who can push-force.

So, I admit: as soon as there's a push-force, there's a risk to do errors. That's true. But there's also many ways to recover from errors, and really, in 3 years of development, I didn't saw a lot of force-pushing mistakes, and when it came to happen we always found a way to recover properly.

So, why is this "Golden Rule of Rebase" being so widely accepted? Is there something else I missed with that? I understand it requires a minimum of organization (every strategy requires some organization), but it works.

答:
The problem with force pushing isn't about your feature branch and master, but about pushing your master to someone else's master - that synchronization is going to be overwriting their master with your changes, ignoring whatever is on their tip.

Considering this danger, there's a reason why you should not be using it at all unless things have screwed up and you absolutely, totally need to use it to effect repairs. A SCM system should not ever need to be forced like this, if it does its because something went horribly wrong (and my first approach in such cases would be to restore backups and repeat the operations to keep the history intact).

So perhaps the question is why are you rebasing at all? For 'clean' history when bringing features back to master? If so, you're throwing out all the good history concerning branching for purely style reasons. IMHO fast-forward merging is also not a best practice either, you should want to keep all history so you can see what you really did, not a sanitised version afterwards.


答:
For software to be highly testable, it must be designed and implemented with testing in mind. This is complementary to Killian Foth's answer, where the software is designed according to a contract, and the test is performed to verify that contract.

"Designing code for testability" means one will have to learn e.g. mocks, stubs, etc. These are various ways to create abstractions and "seams" to allow freedom in substituting software parts.

(The word "seams" is borrowed from the book Working Effectively with Legacy Code  by Michael Feathers. Another recommended book is xUnit Test Patterns: Refactoring Test Code by Gerard Meszaros, which is a heavy one but is totally worth it.)

A language learner may have to learn a lot of things at once. So, it is possible that "designing code for testability" will increase the workload of a learner, and initially slow down the learning progress.

The suggestion is to try both ways. When working on a team, make a good effort to design for testability (and other quality attributes), but each person should also have some solo practice time where the focus is on learning the language itself, or to get something done quickly (because occasionally such need arises), or just to get creative and experiment with something in a completely new, unproven way.

Finally, a programmer who has enough experience with programming and design-for-testability will come to view "broken tests" favorably.

When the test is broken because the implementation changes in some way, if this happens when the programmer does not anticipate this, this is an illuminating moment where the programmer has learned something. For example, the programmer might not anticipate that the code behavior has changed, but the test is telling otherwise. When this happens, the broken test has successfully averted a potential bug.

Title: How can I write unit tests that simplify feature implementation?

Body:
I'm a newbie to working in software development and I read a lot about how cool unit tests are. Now, I've made my first steps into a project where I'm working with a number of equally unexperienced programmers which is why we have produced a bit of spaghetti code. I'm trying to learn how to use testing and other techniques to improve the code quality but one of my newbie co-workers says that tests make things more difficult. Apparently, he has done internships in teams where unit tests were used.

He argued that tests were constantly in his way when he tried to implement a new feature. The tests would fail after he had changed the code. So he had to adapt the tests which of course increased his workload.

But that doesn't make sense to me. I thought tests were supposed to make things easier. So, I suspect that he either didn't implement the features correctly or that the unit tests were badly done. So, I'm wondering: How can I write unit tests so that they don't fail just because a new feature was implemented?


答:
Yes, he's right - writing unit tests does increase your workload, and as you change your code the tests start to fail and you have to update them and that increases your workload even further.

However... that applies when you are changing code that is affected by the tests, typically you write code pieces that are tested by some unit tests and then you do not edit those piece of code again. After all, they work, and you designed them right so adding new features won;t require you to edit them, and I think this is where the problem lies. Inexperienced coders tend to hack code in without enough thought into the future of the codebase. You can add a class with a field, and then suddenly find you need to add another, and the original field needs to change type and so on, this churn is something you learn to avoid by 'getting it right' first time by thinking about what the code is supposed to do and how it will fit in to the product overall, not just solving the immediate problem at hand. Sure, we still need to make such changes, but it happens so much rarely with experienced devs.

One thing that you might find helpful in the intermediate time is using red-green-refactor style of unit testing. This is similar to using a debugger to test, in that you write code then run it in the debugger to see what errors there are, fixing them and repeating the debugging. Only instead of using the debugger, you use an automated test instead. Write the test, run it on the code, update the code and so on.  The trick is to write little bits of code and test them very often and your unit tests become more like mini test harnesses. I find this approach fits better as its very much (conceptually) like the manual testing you're probably doing anyway.


问:
Choosing between Single or multiple projects in a git repository?
In a git environment, where we have modularized most projects, we're facing the one project per repository or multiple projects per repository design issue. Let's consider a modularized project:

```<code>myProject/
   +-- gui
   +-- core
   +-- api
   +-- implA
   +-- implB
</code>```

Today we're having one project per repository. It gives freedom to

release individual components

tag individual components

But it's also cumbersome to branch components as often branching api requires equivalent branches in core, and perhaps other components.

Given we want to release individual components can we still get the similar flexibility by utilizing a multiple projects per repository design.

What experiences are there and how/why did you address these issues?

答: It might be that git-subtree (see Atlassian blog, medium blog, or kernel link) would be a good fit for that you have. So, each of your top level project would use a set of subtree at possibly different version(s).</p>


答: It doesn't matter that value[] is final when none of the methods on String are not. If string class were not final, I could derive and override all the methods and in effect have a mutable string.</p>

Title: Why 'class String' definition has 'final' modifier?

Body:
This answer gives an indication that class String is declared final for thread safety, which does not convince.

This answer does not convince when it says: And so, you make the classes final. There can be no mutable String, because its an immutable class and its final.

Because,

below field with final modifier,

```<code>/** The value is used for character storage. */
    private final char value[];
</code>```

in class String would suffice/indicate that data stored in the created object is suppose to be immutable and thread safe.

So, class String being final has nothing to do with immutability or thread safety.

But it is not clear, why class String is declared final?

Because, as per below class definition, it has final modifier:

```<code>public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
{ .... }
</code>```

So, class String cannot be inherited.

Despite field value[] in class String is declared final, additionaly, What is the necessity for class String also to be final?

Note: Answers to this question will give an idea behind this design decision


问:
Is a private property the same as a public field?
Will a private property same as a public field? Here is the sample code I wrote to understand this:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetSet
{
    class Program
    {
        private int Age_private { get; set; }
        public int Age_public;
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Age_public = 5;
            p.Age_private = 10;  // calling set
            int m = p.Age_public;
            int n = p.Age_private; // calling get
            Console.WriteLine(m);
            Console.WriteLine(n);
            Console.ReadLine();
        }
    }
}
</code>```

Am I doing this correctly?

Also, does it follow that a public field will never require a getter and setter?

Reference: When are Getters and Setters Justified

答:
Yes, this solves your purpose but the story is different.

Fields with getters and setters are known as properties. If you don't set getters and setters explicitly then it's known as member variables or simply variables.

So say, if you code this...

```<code>public int a { get; set; }
private int b { get; set; }
</code>```

These are known as properties.

Or, these are known as member variables.

```<code>public int a;
private int b;
</code>```

Then also, it does the same thing and you can do the assignment and retrieval as like below in both the cases (provided you are not breaking access modifiers logic).

```<code>a = 1;
b = 2;

int c = a;
int d = b;
</code>```

So, this has nothing to do with the approach. You can achieve this with both the approach.

Both the approach has nothing to do with public or private. They are known as Access Modifiers. Public properties / variables can be accessed from anywhere whereas the private properties / variables can be accessed from only within the block it's defined.

Well, then why properties have been introduced? What's the use? The answer is, they have been introduced to implement encapsulation.

Let's say, you have

```<code>private int _unitprice;
private int _quantity;

public int UnitPrice
{
    get
    {
         return _unitprice;
    }
    set
    {
        if(value > 0) _unitprice = value
    }
}

public int Quantity
{
    get
    {
         return _quantity;
    }
    set
    {
        if(value > 0) _quantity = value
    }
}

public int Total
{
    get
    {
         return _unitprice * _quantity;
    }
}
</code>```

Say, you don't want users to access private members _unitprice and _quantity directly, instead access them using public facing properties with / without any validation. I did some validation in the example above, but it's not mandatory.

And some other properties like Quantity which doesn't exists say in table, but we have provided in Business Class for providing the facility and simplicity to the user.

Also, you may notice that Total have only get and no set. So you can even restrict assignment or retrieval using getters and setters.
Hope that helps :)

Body:
Yes, this solves your purpose but the story is different.

Fields with getters and setters are known as properties. If you don't set getters and setters explicitly then it's known as member variables or simply variables.

So say, if you code this...

public int a { get; set; }
private int b { get; set; }

These are known as properties.

Or, these are known as member variables.

public int a;
private int b;

Then also, it does the same thing and you can do the assignment and retrieval as like below in both the cases (provided you are not breaking access modifiers logic).

a = 1;
b = 2;

int c = a;
int d = b;

So, this has nothing to do with the approach. You can achieve this with both the approach.

Both the approach has nothing to do with public or private. They are known as Access Modifiers. Public properties / variables can be accessed from anywhere whereas the private properties / variables can be accessed from only within the block it's defined.

Well, then why properties have been introduced? What's the use? The answer is, they have been introduced to implement encapsulation.

Let's say, you have

private int _unitprice;
private int _quantity;

public int UnitPrice
{
    get
    {
         return _unitprice;
    }
    set
    {
        if(value > 0) _unitprice = value
    }
}

public int Quantity
{
    get
    {
         return _quantity;
    }
    set
    {
        if(value > 0) _quantity = value
    }
}

public int Total
{
    get
    {
         return _unitprice * _quantity;
    }
}

Say, you don't want users to access private members _unitprice and _quantity directly, instead access them using public facing properties with / without any validation. I did some validation in the example above, but it's not mandatory.

And some other properties like Quantity which doesn't exists say in table, but we have provided in Business Class for providing the facility and simplicity to the user.

Also, you may notice that Total have only get and no set. So you can even restrict assignment or retrieval using getters and setters.
Hope that helps :)


问:
Appropriate developer permissions on a dev server?
Should a senior developer be able to have admin permissions (even if it's on a temporary lease basis) to a development server?

I have two specific examples in mind.

I'm the dev lead for Java development and wanted to setup a dedicated development box with git SCM and a jenkins CI server. I was then going to look at something like nexus to archive our builds that we ship to customers.

I'm currently architecting a Java web app and I need to create an application server instance on our dev box for testing. This involves creating a user account for the server to run under.

I've worked in places that allow this kind of permissions (including the current company in a different era) and IMO it helps to drive innovation and progress. This is only a dev box so there's no production data to worry about. The current regime seems overly restrictive and is preventing me from doing my job.

The git example took over 2 years to be setup and I'm still waiting for jenkins. Maybe because they don't really understand what it is. This is hugely frustrating but I actually like the company so I'm wondering how to approach this.

答:
Yes, devs need admin privileges with dev systems. Its just easiest to do this than fumble around asking for access to bits and pieces of the system you need to dev with.

In your case however, you're asking for admin access to the development server to set up tools, not as a developer. So you really should be asking to be the owner/admin of that server with all the responsibilities for keeping it running and maintained. If you have the kind of org that has an admin for that server, you'll need to communicate with him directly so that it is set up for the needs of the developers - so he'll be the one to install Jenkins and set up the user account.

For a dev server, I think letting any dev do whatever they like to it is a bad idea, someone will set things up that they want and break it for others, so its best to have a central point (either an admin or senior dev) as the owner of the box and responsible for the admin activities that are needed for it.


答:
Devs have to have the privileges they need to get their tasks done.

If your task is to install and maintain development tool chains, which include e.g. Jenkins, then of course you need to have the appropriate privileges.

I'm aware that many organizations don't want to decide such stuff case-by-case, but rather have a process which defines something likes privileges globally for the company.

Title: Appropriate developer permissions on a dev server?

Body:
Should a senior developer be able to have admin permissions (even if it's on a temporary lease basis) to a development server?

I have two specific examples in mind.

I'm the dev lead for Java development and wanted to setup a dedicated development box with git SCM and a jenkins CI server. I was then going to look at something like nexus to archive our builds that we ship to customers.

I'm currently architecting a Java web app and I need to create an application server instance on our dev box for testing. This involves creating a user account for the server to run under.

I've worked in places that allow this kind of permissions (including the current company in a different era) and IMO it helps to drive innovation and progress. This is only a dev box so there's no production data to worry about. The current regime seems overly restrictive and is preventing me from doing my job.

The git example took over 2 years to be setup and I'm still waiting for jenkins. Maybe because they don't really understand what it is. This is hugely frustrating but I actually like the company so I'm wondering how to approach this.


问:
Gherkin: What is a reasonable number of scenarios per feature?
I'm keen to get thoughts on a reasonable number of scenarios per feature in Gherkin.

At what point do you start to thing about re-organising the feature to keep the number of scenarios at a manageable level?

答:
Like in all testing, it depends on what you are testing. Complex features, which require lots of steps and preperations for example, will need multiple scenarios to be tested thoroughly, where a simple calculation feature may do with only the happy flow and two erroneous scenarios.

If you find yourself writing too many scenarios for one feature, it may be an indication that the feature is too big.

But in the end, there isn't a "Golden Number" of tests before you can say: "Jup, I've reached my amount, it should be all right", it depends on multiple factors (Complexity, amount of possibilities, the person writing the tests etc).

If you start losing track of your scenarios, its probably a good time to re-organise :)


问:
Automatic deployment of windows desktop application
I work on commercial (windows) desktop application that is subjected to frequent changes, and is installed on multiple locations. Application should only be available to existing users. Until now each change was applied through downloaded installer. I would like to create some form of automatic update architecture.

I would like to know is there some built in windows solution to that problem, either through windows or .NET framework?

答: The usual way to do this is to update an application that is packaged into a Windows installer msi using group policy. Its quite easy to do as long as you're a doman admin in an AD domain.</p>


问:
Constructor Injection vs. IocFactory
Today at work a collegue and I had a discussion about the following:

Basically we have a rule engine which works in the following way:

RuleExecutor

Gets all rules to execute in the constructor like public RuleExecutor(ICollection<IRule> rulesToExecute) { ... }

Executes all rules by calling rule.ApplyRule(); for each rulesToExecute

Rules

Provide method ApplyRule(); which executes the rule

Now we want the RuleExecutor to be executed in a cron job.

We had a discussion about how to retrieve an instance of the RuleExecutor.

I think the "correct way" is via constructor injection

```<code>public RuleCronJob(IRuleExecutor ruleExecutor) { ... }
</code>```

My collegue wants to use a "IocFactory" which has a static method GetInstance<>.
So in the "execute method" of the cron job he would do something like var ruleExecutor = IocFactory.GetInstance<IRuleExecutor>();

```<code>public static TType GetInstance<TType>(params Tuple<string, object>[] constructorParameters)
    {
        if (constructorParameters.Any())
        {
            var constructorArgs = new Collection<ConstructorArgument>();
            foreach (var parameter in constructorParameters)
            {
                constructorArgs.Add(new ConstructorArgument(parameter.Item1, parameter.Item2, true));
            }

            return Kernel.Value.Get<TType>(constructorArgs.Cast<IParameter>().ToArray());
        }

        return Kernel.Value.Get<TType>();
    }
</code>```

Kernel is a StandardKernel of Ninject.

I think the constructor injection is better because it allows for easier tests (mocking) etc. but I couln't convince him to use it because he thinks that the IocFactory "works as well so why not use it"...

What would be some arguments to convince him to use constructor injection instead of the IocFactory?

答:
but I couln't convince him to use it because he thinks that the IocFactory "works as well so why not use it"...

Because it's more complicated?

Rather by definition, code that is doing more things has more things that can go wrong. For IoC containers, that often means lots of things going on under the covers to discover the various dependencies, resolve them, inject them...  IoC containers are the nuclear option for dependency injection. They'll solve your problem, but are almost always overkill, and will leave nasty lingering effects around regardless.

Title: Constructor Injection vs. IocFactory


答:
Christopher did a very good job of enumerating the disadvantages of a one-project-per-repository model.  I would like to discuss some of the reasons you might consider a multiple-repository approach.  In many environments I have worked in, a multi-repository approach has been a reasonable solution, but the decision of how many repositories to have, and where to make the cuts has not always been an easy one to make.

In my current position, I migrated a behemoth single-repository CVS repository with over ten years of history into a number of git repositories.  Since that initial decision, the number of repositories has grown (through the actions of other teams), to the point where I suspect we have more than would be optimal.  Some new-hires have suggested merging the repositories but I have argued against it.  The Wayland project has a similar experience.  In a talk I saw recently, they had, at one point, over 200 git repositories, for which the lead apologized.  Looking at their website, I see now they are at 5, which seems reasonable.  It's important to observe that joining and splitting repositories is a manageable task, and it's okay to experiment (within reason).

So when might you want multiple repositories?

A single repository would be too large to be efficient.

Your repositories are loosely coupled, or decoupled.

A developer typically only needs one, or a small subset of your repositories to develop.

You typically want to develop the repositories independently, and only need to synchronize them occasionally.

You want to encourage more modularity.

Different teams work on different repositories.

Points 2 and 3 are only significant if point 1 holds.  By splitting our repositories,  I significantly decreased the delays suffered by our offsite colleagues, reduced disk consumption, and improved network traffic.

4 and 5 are more subtle.  When you split the repos of say a client and server, this makes it more costly to coordinate changes between the client and server code.  This can be a positive, in that encourages a decoupled interface between the two.

Even with the downsides of multi-repository projects, a lot of respectable work is done that way -- wayland and boost come to mind.  I don't believe a consensus regarding best practices has evolved yet, and some judgement is required.  Tools for working with multiple repositories (git-subtree, git-submodule and others) are still being developed and experimented with.  My advice is to experiment and be pragmatic.

Title: Choosing between Single or multiple projects in a git repository?

Body:
In a git environment, where we have modularized most projects, we're facing the one project per repository or multiple projects per repository design issue. Let's consider a modularized project:

```<code>myProject/
   +-- gui
   +-- core
   +-- api
   +-- implA
   +-- implB
</code>```

Today we're having one project per repository. It gives freedom to

release individual components

tag individual components

But it's also cumbersome to branch components as often branching api requires equivalent branches in core, and perhaps other components.

Given we want to release individual components can we still get the similar flexibility by utilizing a multiple projects per repository design.

What experiences are there and how/why did you address these issues?


问:
What's the point of implementing a Stack using two queues?
I have the following homework question:

Implement the stack methods push(x) and pop() using two queues.

This seems odd to me because:

A Stack is a (LIFO) queue

I don't see why you would need two queues to implement it

I searched around:

GeeksForGeeks

StackOverflow

and found a couple solutions. This is what I ended up with:

```<code>public class Stack<T> {
    LinkedList<T> q1 = new LinkedList<T>();
    LinkedList<T> q2 = new LinkedList<T>();

    public void push(T t) {
        q1.addFirst(t);
    }

    public T pop() {
        if (q1.isEmpty()) {
            throw new RuntimeException(
                "Can't pop from an empty stack!");
        }

        while(q1.size() > 1) {
            q2.addFirst( q1.removeLast() );
        }

        T popped = q1.pop();

        LinkedList<T> tempQ = q1;
        q1 = q2;
        q2 = tempQ;

        return popped;
    }
}
</code>```

But I don't understand what the advantage is over using a single queue; the two queue version seems pointlessly complicated.

Say we choose for pushes to be the more efficient of the 2 (as I did above), push would remain the same, and pop would simply require iterating to the last element, and returning it. In both cases, the push would be O(1), and the pop would be O(n); but the single queue version would be drastically simpler. It should only require a single for loop.

Am I missing something? Any insight here would be appreciated.

答:
It's hard to imagine a use for such an implementation, it's true. But most of the point is to prove that it can be done.

In terms of actual uses for these things, however, I can think of two. One use for this is implementing systems in constrained environments that weren't designed for it: for example, Minecraft's redstone blocks turn out to represent a Turing-complete system, which people have used to implement logic circuits and even entire CPUs. In the earliest days of script-driven gaming, many of the first game bots were also implemented this way.

But you can also apply this principle in reverse, ensuring that something isn't possible in a system when you don't want it to be. This can come up in security contexts: for example, powerful configuration systems can be an asset, but there are still degrees of power that you might rather not give to users. This constrains what you can allow the configuration language to do, lest it be subverted by an attacker, but in this case, that's what you want.