问:
How can I get the transit time for packets for a jitter buffer?
I'm trying to wrap my head around the concept of a real jitter buffer. I'm basing the only knowledge that I have around this article:

http://toncar.cz/Tutorials/VoIP/VoIP_Basics_Jitter.html

This article states that:

In the jitter estimator formula, the value D(i-1, i) is the
  difference of relative transit times for the two packets. The
  difference is computed as

D(i,j) = (Rj - Ri) - (Sj - Si) = (Rj - Sj) - (Ri - Si)

Si is the timestamp from the packet i and Ri is the time of arrival
  for packet i.

I've been trying to figure out in my head how it's possible to get the time it takes a packet to get from one system to the other even using TCP. If I'm not mistaken, won't the timestamps on the two devices be out of sync even if I were to send them as headers? Even if I were to sync timestamps before beginning pushing out the audio data, wouldn't that be received several milliseconds afterwards making syncing not possible?

So my question is, how can I actually calculate how long it takes for packets to arrive at their destination to calculate jitter?

答:
The absolute time it takes for packets to arrive at their destination is called latency.  Jitter is the relative difference between those times.  The distinction is important, because due to a fortunate quirk of the math, you don't actually need to know the latency in order to calculate the jitter.

Let's say the sender's clock is t milliseconds faster than the receiver's clock.  t changes over time due to drift, but in the 20 milliseconds between packets, that drift is essentially negligible.  That means we must add t to every receiver timestamp in order to synchronize it with the sender's timestamp.  Correcting for the unsynchronized clocks, the formula becomes:

```<code>D(i,j) = ((Rj + t) - (Ri + t)) - (Sj - Si)
</code>```

Notice anything?  Because we are only interested in the difference between timestamps, the t cancels out!  If we really want to calculate t, and subsequently the latency, we can do it using techniques I described here, but it's not necessary if we only care about jitter.

Body:
The absolute time it takes for packets to arrive at their destination is called latency.  Jitter is the relative difference between those times.  The distinction is important, because due to a fortunate quirk of the math, you don't actually need to know the latency in order to calculate the jitter.

Let's say the sender's clock is t milliseconds faster than the receiver's clock.  t changes over time due to drift, but in the 20 milliseconds between packets, that drift is essentially negligible.  That means we must add t to every receiver timestamp in order to synchronize it with the sender's timestamp.  Correcting for the unsynchronized clocks, the formula becomes:

D(i,j) = ((Rj + t) - (Ri + t)) - (Sj - Si)

Notice anything?  Because we are only interested in the difference between timestamps, the t cancels out!  If we really want to calculate t, and subsequently the latency, we can do it using techniques I described here, but it's not necessary if we only care about jitter.


问:
Is testable code better code?
I'm attempting to get into the habit of writing unit tests regularly with my code, but I've read that first it's important to write testable code.
This question touches on SOLID principles of writing testable code, but I want to know if those design principles are beneficial (or at least not harmful) without planning on writing tests at all. To clarify - I understand the importance of writing tests; this is not a question on their usefulness.

To illustrate my confusion, in the piece that inspired this question, the writer gives an example of a function that checks the current time, and returns some value depending on the time. The author points to this as bad code because it produces the data (the time) it uses internally, thus making it difficult to test. To me, though, it seems like overkill to pass in the time as an argument. At some point the value needs to be initialized, and why not closest to consumption? Plus, the purpose of the method in my mind is to return some value based on the current time, by making it a parameter you imply that this purpose can/should be changed. This, and other questions, lead me to wonder if testable code was synonymous with "better" code.

Is writing testable code still good practice even in the absence of tests?

Is testable code actually more stable? has been suggested as a duplicate. However, that question is about the "stability" of the code, but I am asking more broadly about whether the code is superior for other reasons as well, such as readability, performance, coupling, and so forth.

答:
If you are going with SOLID principles you will be on the good side, especially if extend this with KISS, DRY, and YAGNI.

One missing point for me is the point of the complexity of a method. Is it a simple getter/setter method? Then just writing tests to satisfy your testing framework would be a waste of time.

If it's a more complex method where you manipulate data and want to be sure that it will work even if you have to change the internal logic, then it would be a great call for a test method. Many times I had to change a piece of code after several days/weeks/months, and I was really happy to have the test case. When first developing the method I tested it with the test method, and I was sure that it will work. After the change my primary test code still worked. So I was certain that my change didn't break some old code in production.

Another aspect of writing tests is to show other developers how to use your method. Many times a developer will search for an example on how to use a method and what the return value will be.

Just my two cents.

ContentLicense: CC BY-SA 3.0

Title: Is testable code better code?


问:
Improve bisection method or alternate algorithm for efficient determination of text font size to fit in a box
I need to find the font size of a text that fits in a box.

Given my current font size, I can get the bounding rectangle of the text.

If I set some arbitrary min and max font size, I suppose I can increment or decrement my font size until I get to the given box.

I am thinking bisection method:

```<code>ChangeFontMethod(float currentFont, float reqWidth)

    float minFont = 1, maxFont = 1000
    int tolerance = 0.001, maxIter = 1000
    int n = 1

    float currentWidth = textWithCurrentFont.boundingRect.Width

    do
        if currentWidth = reqWidth
            break
        else if currentWidth < reqWidth
            minFont = currentFont
        else
            maxFont = currentFont

        if maxFont - minFont < tolerance
            break

        currentFont = (minFont + maxFont)/2
        currentWidth = textWithCurrentFont.boundingRect.Width
        n++

    while n <= maxIter

    return currentFont
</code>```

From what I read it should have logarithmic speed, but also I read that it is "slow"

Is there a better way ?

I don't know if I can improve my search by assuming a relationship between font size and font width - definitely there is one, but it's non-linear. So I don't know how to even improve the speed by a better "first guess"

答:
I am not going to code it but I will give you a math approach. Assuming you know the resulting width with two different font sizes:

font size 1 (s1) implies text width 1 (w1) (the small value)

font size 2 (s2) implies text width 2 (w2) (the bigger value)

then your linear estimate of size (s3) that will fit the required width (w) is from using manipulating this formula:

(s3-s1)/(s2-s1)=(w-w1)/(w2-w1)

so
estimate correct width is

s3 = s1+(w-w1)*(s2-s1)/(w2-w1)

now you check w3 (the width when using s3). If w < w3 then repeat the method but using s1,w1,s3,w3 if w > w3 then repeat the method but using s3,w3,s2,w2.

This iterative approach only requires that the width for a given text is a monotonic function of the font size, in other words doesn't matter if linear but it will converge faster if the function is closer to linear, so it will accelerate convergence as the range of font sizes reduces.


问:
Managing Production Issues during a Scrum Sprint
The question of managing bugs in production has been a large feature in my mind of late. Sprint's are not meant to have any items added into them, but for critical bugs, this is simply unavoidable.

How does one go about managing this break in the sprint? Do you simply give a sprint a percentage "allowance" of time, thus only filling say 80% of the schedule with sprint items "just in case"?

答:
I work in a team that does mostly development work, but is also responsible for existing complex systems. We've had this problem as well.

Basically, we estimate our points based on the last sprint(s) and then reserve a number of points for the expected maintenance work. Should a maintenance task occur that exceeds this significantly, like a major outage, we add it as a user story and remove an existing one that has not started yet, to keep the sprint of the same size. If a major issue pops up that is less urgent, we move it into the next sprint.

Yes, this is technically not following scrum. But the flexibility has worked well for us.

We have refined this reserved time by asking the team at every planning meeting whether they see reason to deviate from the standard reservation. We introduced this after doing an office move which took us much more time than we anticipated, leading to many stories not being finished.

However, do not just stick to how my team or any other team does it. Pick something, and just do it. There is no way to ensure that it will work well for your team. Try, and evaluate in the retrospective. If the team is unhappy, try something different and evaluate again. All teams are different, and their needs and limitations are different as well.

ContentLicense: CC BY-SA 2.5


问:
Should I automatically install needed modules?
I'm writing a program for my grandpa. Occasionally an update will require a new module that's not installed on his computer. I don't want to have to manually install new modules every time, but he's not tech savvy enough to figure it out himself.

Is it OK for me to check for ImportErrors and install a module from the error message? If not, what's the alternative?

答:
This is the job of the package manager. In the case of Python: pip.

If you package the library you are building and specify its dependencies, your users (grandpa), will simply need to run:

$ pip install --upgrade <name-of-package>

to get the latest version you've released and all of its dependencies. If you don't want to publish your code online, pip can also install from local sources:

$ pip install zipped_package_emailed_to_grandpa.zip

or, if you really need to package this in a single (Python 3.4+) script, you could call pip from within:

```<code>#!/usr/bin/env python3

def main():
   ...

if __name__ == '__main__':
    import sys, subprocess
    dependencies = ['dep_1', 'dep_2']
    subprocess.call([sys.executable, '-m', 'pip', 'install'] + dependencies)
    import dep_1, dep_2
    main()
</code>```

but this is definitely uncommon.

Body:
This is the job of the package manager. In the case of Python: pip.

If you package the library you are building and specify its dependencies, your users (grandpa), will simply need to run:

$ pip install --upgrade <name-of-package>

to get the latest version you've released and all of its dependencies. If you don't want to publish your code online, pip can also install from local sources:

$ pip install zipped_package_emailed_to_grandpa.zip

or, if you really need to package this in a single (Python 3.4+) script, you could call pip from within:

#!/usr/bin/env python3

def main():
   ...

if __name__ == '__main__':
    import sys, subprocess
    dependencies = ['dep_1', 'dep_2']
    subprocess.call([sys.executable, '-m', 'pip', 'install'] + dependencies)
    import dep_1, dep_2
    main()

but this is definitely uncommon.


问:
Does knowing Latin or other logical languages contribute to being a better programmer?
I'm currently studying Latin at school, and what I've learned is that it's a very logical language. I feel this has contributed to my programming ability, as it makes it my code easier to understand.

Is there any relation between knowledge of a very logical language such as Latin and the comprehension of code?

答: At one time students who were interested in science or engineering were encouraged to take Latin as opposed to French or Spanish. I know personally I struggled with it. I can't deny that it help my vocabulary, but I can't see where it help me be a better programmer.</p>


问:
Is message-oriented middleware applicable for intra-application communication?
I recently developed an application in LabVIEW, but although I'm pretty happy with its design I realised that I might be able to improve one part of it by making the various components of this particular subsystem collaborate with each other using a publisher/subscriber model.

If I do go down this road, I think it's best to develop a "Message Bus" LabVIEW library that I can reuse in various projects including the one I've just made. To get a good idea of how to design this, I've been looking at message-oriented middleware solutions like RabbitMQ and reading through Gregor Hohpe's Enterprise Integration Patterns which focuses on this sort of area.

All of these things keep talking about how MOMs should be used to integrate separate applications (that may or may not be running on the same machine). It just irks me a little that I can't seem to find any discussion about MOMs being used just as simple mediator classes that exist purely within the scope of one instance of a running application and only serve to facilitate communication between objects within that running instance.

Essentially my question is whether it's sensible to develop a message bus for this sort of thing. Can (and should) middleware like RabbitMQ be used for mediating between objects running within the same application?

答:
There's a few things to consider.  If you're talking about "Communicating" inside of a single application, the usual route is to create an object or data structure that holds the data you want to communicate, and simply giving it to the class/method that will use it.

It's fairly common to want to share information between different threads, in which case all threads need to have access to the variable somehow, and you need to deal with concurrency issues.

MOMs usually don't work on the intra-process level, because passing objects/data is far more convenient when considering just one process.  A MOM will simplify communication in the case where information has to be shared amongst various processes.

It's sort of like this: You and I use the same language.  If you tell me to go refill your cup of coffee, I know how to do it.  I might do it begrudgingly, but I know what to do.  This kind of communication is what you have inside your own process - everyone understands each other.  You just need to figure out a way of getting the right data from one entity to another.

A MOM comes into play when you want to talk to someone who won't understand you(another process).  There's a lot of work that goes into transmitting information.  You might think it's simple to send a Boolean or an array of integers, but it can get very involved.  What is a Boolean? A bit? A byte? An integer?  What's an Integer(let alone an integer array)? Are they 8 bits, 16 bits, 32 bits, 64 bits?  The MOM on one end will basically take care of the hassle of sending a message that says "I'm sending you an array with 20 values which are 32-bit integers" followed by said array.  The receiving MOM understands the message and can process it.  The reason you don't use a MOM inside a process is because these kinds of messages take up more space than what's necessary.

If I'm one subroutine and you're another, all I need to do is write the array to an agreed-upon location in memory(a variable), and you'll be able to see the array.  We may have agreed upon the size of the array ahead of time(ie pre-compilation) but even that doesn't need to be communicated in some cases.  You're effectively using the language, compilation, and typing system as your MOM in this case, because those are the things that give meaning to "The array starts at address 0xDEADBEEF and uses 512 bytes of memory".

Now, you could still use a MOM to send things inside the same process, by pointing the sender and receiver at the loopback address, but this is a lot of overhead when simply passing variables/parameters is what you're really doing.

Edit: A concrete example with Java

Per OP's coupling concerns, I'd like to present a concrete example of sharing messages in Java that has minimal coupling between components.  I've used this on several projects and it's fairly straight forward.

The base of it is to use an object like a BlockingQueue.  If you don't want to read the documentation the take-away is that this is a thread-safe queue that allows multiple threads to put things in, and take them out without you having to worry about concurrency.  So you'd end up with something like BlockingQueue<Message>.  The next step is to get this object in the hands of the threads that will use it.  That means you either pass the reference to the object to each thread, or you can wrap the queue itself in a singleton.

A simple implementation where you can pass the reference to a thread:

```<code>public class Producer implements Runnable {
    BlockingQueue<Message> queue;
    @Override
    public void run() {
        // TODO : Produce messages
    }
    public void initialize(BlockingQueue<Message> q) {
        queue = q;
    }
}
</code>```

And the calling code:

```<code>// Just a compile-able example of initializing such a queue:
BlockingQueue<Message> queue = new ArrayBlockingQueue<Message>(200);

// ...

Producer producer = new Producer();
producer.initialize(queue);
Thread t = new Thread(producer);
t.start();
</code>```

Consumers of these messages would look very similar.  But you can already see that it becomes very simple to make multiple types of producers(and consumers), and all of these producers/consumers are merely coupled to a queue.  Whether it's a MockProducer, DemoProducer, RealProducer, RealConsumer, etc, the only coupling between them is the queue. The 'communication' between producers and consumers is basically whether the queue is full, empty, or somewhere in between. (And what you would do in each of these states is another discussion entirely)

Of course there are other options besides queues - you can utilize any data structure you want, with any messaging protocol you can implement.  You just need to be concerned about the thread-safety of your reads/writes to the data structure.  I chose the queue though because it closely resembles my experience with reading/writing from a MOM - Is there a Message? Then I'll consume it.  Can I put something there? Then I'll produce a message.

Body:
There's a few things to consider.  If you're talking about "Communicating" inside of a single application, the usual route is to create an object or data structure that holds the data you want to communicate, and simply giving it to the class/method that will use it.

It's fairly common to want to share information between different threads, in which case all threads need to have access to the variable somehow, and you need to deal with concurrency issues.

MOMs usually don't work on the intra-process level, because passing objects/data is far more convenient when considering just one process.  A MOM will simplify communication in the case where information has to be shared amongst various processes.

It's sort of like this: You and I use the same language.  If you tell me to go refill your cup of coffee, I know how to do it.  I might do it begrudgingly, but I know what to do.  This kind of communication is what you have inside your own process - everyone understands each other.  You just need to figure out a way of getting the right data from one entity to another.

A MOM comes into play when you want to talk to someone who won't understand you(another process).  There's a lot of work that goes into transmitting information.  You might think it's simple to send a Boolean or an array of integers, but it can get very involved.  What is a Boolean? A bit? A byte? An integer?  What's an Integer(let alone an integer array)? Are they 8 bits, 16 bits, 32 bits, 64 bits?  The MOM on one end will basically take care of the hassle of sending a message that says "I'm sending you an array with 20 values which are 32-bit integers" followed by said array.  The receiving MOM understands the message and can process it.  The reason you don't use a MOM inside a process is because these kinds of messages take up more space than what's necessary.

If I'm one subroutine and you're another, all I need to do is write the array to an agreed-upon location in memory(a variable), and you'll be able to see the array.  We may have agreed upon the size of the array ahead of time(ie pre-compilation) but even that doesn't need to be communicated in some cases.  You're effectively using the language, compilation, and typing system as your MOM in this case, because those are the things that give meaning to "The array starts at address 0xDEADBEEF and uses 512 bytes of memory".

Now, you could still use a MOM to send things inside the same process, by pointing the sender and receiver at the loopback address, but this is a lot of overhead when simply passing variables/parameters is what you're really doing.

Edit: A concrete example with Java

Per OP's coupling concerns, I'd like to present a concrete example of sharing messages in Java that has minimal coupling between components.  I've used this on several projects and it's fairly straight forward.

The base of it is to use an object like a BlockingQueue.  If you don't want to read the documentation the take-away is that this is a thread-safe queue that allows multiple threads to put things in, and take them out without you having to worry about concurrency.  So you'd end up with something like BlockingQueue<Message>.  The next step is to get this object in the hands of the threads that will use it.  That means you either pass the reference to the object to each thread, or you can wrap the queue itself in a singleton.

A simple implementation where you can pass the reference to a thread:

public class Producer implements Runnable {
    BlockingQueue<Message> queue;
    @Override
    public void run() {
        // TODO : Produce messages
    }
    public void initialize(BlockingQueue<Message> q) {
        queue = q;
    }
}

And the calling code:

// Just a compile-able example of initializing such a queue:
BlockingQueue<Message> queue = new ArrayBlockingQueue<Message>(200);

// ...

Producer producer = new Producer();
producer.initialize(queue);
Thread t = new Thread(producer);
t.start();

Consumers of these messages would look very similar.  But you can already see that it becomes very simple to make multiple types of producers(and consumers), and all of these producers/consumers are merely coupled to a queue.  Whether it's a MockProducer, DemoProducer, RealProducer, RealConsumer, etc, the only coupling between them is the queue. The 'communication' between producers and consumers is basically whether the queue is full, empty, or somewhere in between. (And what you would do in each of these states is another discussion entirely)

Of course there are other options besides queues - you can utilize any data structure you want, with any messaging protocol you can implement.  You just need to be concerned about the thread-safety of your reads/writes to the data structure.  I chose the queue though because it closely resembles my experience with reading/writing from a MOM - Is there a Message? Then I'll consume it.  Can I put something there? Then I'll produce a message.


问:
Why is SRP using the class construct to contain a responsibility opposed to using any other OOP entity?
SRP states ...

There should never be more than one reason for a class to change.

But why a class?  Why not use granularity of a function/method?  What instead of separating my functionality into separate classes, I separate it into separate functions?

I don't claim that this works or is advisable in all cases, but in some cases with a few modifications it is fairly similar.  When something needs to change I can go to that function and change it.  While it may not be applicable to all situations, I often come across situations where I create a new class to single out a responsibility when I can just create a new function inside a class and it will work just as well.

Example -- Before Separation

class ProductDataMapper
{
    function findById($id)
    {
        // data retrieval concern i.e. read info from DB
        $data = array('name' => 'Mike');

        // data-to-object mapping concern
        $productParams = array();
        $productParams['name'] = $data['name_column'];

        $product = new Product($productParams);

        return $product;
    }
}
```

<p><strong>Example -- After Separation</strong>    </p>

```class ProductDataMapper
{
    function findById($id)
    {
        $data = $this->dataConcern($id);
        $productParams = $this->mappingConcern($data);
        $product = new Product($productParams);
        return $product;
    }

    function dataConcern($id)
    {
        $data = $db->get("SELECT...$id");
        return $data;
    }

    function mappingConcern($data)
    {
        $productParams = array();
        $productParams['name'] = $data['name_column'];
        return $productParams;
    }
}
```

So if My SQL table changes but data remains the same, I only need to change one method ::dataConcern().  If my binding changes between the schema and object parameters, all I need to change is ::mappingConcern().

Why create a whole other classes to handle those responsibilities?

答:
Why create a whole other classes to handle those responsibilities?

Because when you're doing Object Oriented Programming, your focus should be on the objects. They are your unit of work for making the design and providing abstraction. And most importantly, they are your unit of reuse. By letting them change for different reasons, you're forcing people who are using them for one reason be impacted by a change made to another reason that they don't care about.

I am on record as saying that SRP works just as well through the lens of functional/imperative programming. The difference is that in those paradigms, your unit of reuse isn't a class, but a function or module.


问:
What would this interface be called?
At work we have a java backend that talks to python on some mobile devices. The mobile devices have no GUI, it's just pure string manipulation. All contact is initiated by the python; the java is just for listening and answering.

As such the python will send messages like:

```<code>message_name(field1, field2, field 3)
</code>```

As strings. The listener then picks it up, finds the associated class for message_name (which is defined in an XML file) and feeds it the fields. The class then feeds the listener a response which is just a csv like so:

```<code>response_field1, response_field2, response_field3
</code>```

I'm not overly familiar with this kind of interface (or really any client-server interfaces), but I'm fairly sure it's not REST or SOAP. I'm not sure if it even has a name, or is simply a homegrown kind of thing. None of my coworkers have a name for it.

In response to comment by @moberemk the XML file looks something like this (for the above message/response):

```<code><bean id="command_name" parent="base_request_class"
      class="the_class_that_takes_the_request"
      scope="prototype">
    <property name="readOnly" value="true"/>
    <property name="commandName"  value="message_name" />
    <property name="response" ref="name_of_response_bean" />
    <property name="args">
         <list>
             <value>field1</value>
             <value>field2</value>
             <value>field3</value>
         </list>
    </property>
</bean>

<bean id="name_of_response_bean"
      class="base_response_class
      scope="prototype">
    <property name="fields">
         <list>
             <value>response_field1</value>
             <value>response_field2</value>
             <value>response_field3</value>
         </list>
    </property>
</bean>
</code>```

The listener makes note of this XML file. It then, upon receiving a message, looks for a relevant bean with "commandName" = "message_name" for whatever "message_name" came through. It then feeds the fields in the list of fields (args) to the class (given by the bean property "class"). Then the listener, once the thread for the class that takes the request has finished, takes the return result of that class and sends it verbatim to the python device.

So, if the listener were a human the process would go something like:

```<code><receives message>
<looks at message name>
"Oh, it's a $message_name type of message. I know where to find who can help"
<Looks up who handles that kind of message>
<sends him the message with note "Let me know what you get back!">
<Guy that handles that message does his message handling, tells the listener what he found>
<Listener returns that to the device>
</code>```

With some python pseudocode...

```<code>def listener(self, cmd):
    parsed = []
    parsed = self.parse(cmd) #Array with ["name", "field1", "field2" ...]
    class = self.find_matching_class(parsed[0]) #looks through the XML for the name of the class that should handle this message. String type
    executor = getattr(sys.modules[__name__], class) #Gets an instance of the class related to the message
    response = executor.execute(response[1:])
    self.connection.sendall(response) #Sends the response created by the 'executor' class back to the device that asked for it
</code>```

答: That interface is a RPC - Remote Procedure Call. "RPC" is not a protocol but a family of protocols - there are many standardized RPC protocols, and countless standardless ones - your's probably being one of them - so I don't think it has a specific well known name...</p>

Title: What would this interface be called?


问:
Why isn't there a typeclass for functions?
In a learning problem I've been messing around with, I realised I needed a typeclass for functions with operations for applying, composing etc. Reasons...

It can be convenient to treat a representation of a function as if it were the function itself, so that applying the function implicitly uses an interpreter, and composing functions derives a new description.

Once you have a typeclass for functions, you can have derived typeclasses for special kinds of functions - in my case, I want invertible functions.

For example, functions that apply integer offsets could be represented by an ADT containing an integer. Applying those functions just means adding the integer. Composition is implemented by adding the wrapped integers. The inverse function has the integer negated. The identity function wraps zero. The constant function cannot be provided because there's no suitable representation for it.

Of course it doesn't need to spell things as if it the values were genuine Haskell functions, but once I had the idea, I thought a library like that must already exist and maybe even using the standard spellings. But I can't find such a typeclass in the Haskell library.

I found the Data.Function module, but there's no typeclass - just some common functions that are also available from the Prelude.

So - why isn't there a typeclass for functions? Is it "just because there isn't" or "because it's not so useful as you think"? Or maybe there's a fundamental problem with the idea?

The biggest possible problem I've thought of so far is that function application on actual functions would probably have to be special-cased by the compiler to avoid a looping problem - in order to apply this function I need to apply the function application function, and to do that I need to call the function application function, and to do that...

More Clues

Example code to show what I'm aiming for...

```<code>{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}

--  In my first version, Doable only had the one argument f. This version
--  seemed to be needed to support the UndoableOffset type.
--
--  It seems to work, but it also seems strange. In particular,
--  the composition function - a and b are in the class, but c isn't,
--  yet there's nothing special about c compared with a and b.
class Doable f a b where
  fwdApply :: f a b -> a -> b
  compDoable :: f b c -> f a b -> f a c

--  In the first version, I only needed a constraint for
--  Doable f a b, but either version makes sense.
class (Doable f a b, Doable f b a) => Undoable f a b where
  bwd      :: f a b -> f b a

  bwdApply :: f a b -> b -> a
  bwdApply f b = fwdApply (bwd f) b

--  Original ADT - just making sure I could wrap a pair of functions
--  and there were no really daft mistakes.
data UndoableFn a b = UFN { getFwd :: a -> b, getBwd :: b -> a }

instance Doable UndoableFn a b where
  fwdApply = getFwd
  compDoable f g = UFN ((getFwd f) . (getFwd g)) ((getBwd g) . (getBwd f))

instance Undoable UndoableFn a b where
  bwd f    = UFN (getBwd f) (getFwd f)
  bwdApply = getBwd

--  Making this one work led to all the extensions. This representation
--  can only represent certain functions. I seem to need the typeclass
--  arguments, but also to need to restrict which cases can happen, hence
--  the GADT. A GADT with only one constructor still seems odd. Perhaps
--  surprisingly, this type isn't just a toy (except that the whole thing's
--  a toy really) - it's one real case I need for the exercise. Still a
--  simple special case though.
data UndoableOffset a b where
  UOFF :: Int -> UndoableOffset Int Int

instance Doable UndoableOffset Int Int where
  fwdApply (UOFF x) y = y+x
  compDoable (UOFF x) (UOFF y) = UOFF (x+y)

instance Undoable UndoableOffset Int Int where
  bwdApply (UOFF x) y = y-x
  bwd (UOFF x) = UOFF (-x)

--  Some value-constructing functions
--  (-x) isn't shorthand for subtraction - whoops.
undoableAdd :: Int -> UndoableFn Int Int
undoableAdd x = UFN (+x) (\y -> y-x)

undoableMul :: Int -> UndoableFn Int Int
undoableMul x = UFN (*x) (`div` x)

--  With UndoableFn, it's possible to define an invertible function
--  that isn't invertible - to break the laws. To prevent that, need
--  the UFN constructor to be private (and all public ops to preserve
--  the laws). undoableMul is already not always invertible.
validate :: Undoable f a b => Eq a => f a b -> a -> Bool
validate f x = (bwdApply f (fwdApply f x)) == x

--  Validating a multiply-by-zero invertible function shows the flaw
--  in the validate-function plan. Must try harder.
main = do putStrLn . show $ validate (undoableAdd 3) 5
          putStrLn . show $ validate (undoableMul 3) 5
          --putStrLn . show $ validate (undoableMul 0) 5
          fb1 <- return $ UOFF 5
          fb2 <- return $ UOFF 7
          fb3 <- return $ compDoable fb1 fb2
          putStrLn $ "fwdApply fb1  3 = " ++ (show $ fwdApply fb1  3)
          putStrLn $ "bwdApply fb1  8 = " ++ (show $ bwdApply fb1  8)
          putStrLn $ "fwdApply fb3  2 = " ++ (show $ fwdApply fb3  2)
          putStrLn $ "bwdApply fb3 14 = " ++ (show $ bwdApply fb3 14)
</code>```

The application involves a kind of unification where unified values aren't equal, but are related via those invertible functions - Prolog-style logic but with a = f(b) constraints rather than a = b. Most of the composition will result from optimizing a union-find structure. The need for inverses should be obvious.

If no item in a unified set has an exact value, then a particular item can only be quantified relative to another item in that unified set. That's why I don't want to use "real" functions - computing those relative values. I could drop the whole function aspect and just have absolute and relative quantities - I probably only need numbers/vectors and (+) - but my inner architecture astronaut wants his fun.

The only way I break the links apart again is via backtracking, and everything is pure - union-find will be done using keys into an IntMap as "pointers". I have simple union-find working, but as I haven't added the invertible functions yet, there's no point listing it here.

Reasons I can't use Applicative, Monad, Arrow etc

The main operations I need the function abstraction class to provide are application and composition. That sounds familiar - e.g. the Applicative (<*>), Monad (>>=) and Arrow (>>>) are all composition functions. However, the types that implement the function abstraction in my case will contain some data structure that represents a function, but which isn't (and can't contain) a function, and which can only represent some limited set of functions.

As I mentioned in the explanation of the code, sometimes I can only quantify one item relative to another because no item in a "unified" cluster has an exact value. I want to be able to derive a representation of that function, which in general will be the composition of several provided functions (walking up to a common ancestor in the union/find tree) and of several inverse functions (walking back down to the other item).

Simple case - where the original "functions" are limited to integer-offset "functions", I want the composed result as an integer-offset "function" - add the component offsets. That's a big part of why the composition function needs to be in the class as well as the application function.

This means I cannot provide the operations pure, return or arr for my types, so I can't use Applicative, Monad or Arrow.

This isn't a failure of those types - it's a mismatch of abstractions. The abstraction I want is of a simple pure function. There's no side-effecting, for example, and no need to build a convenient notation for sequencing and composing the functions other than an equivalent of the standard (.) that applies to all functions.

I could instance Category. I'm confident that all my functiony-things will be able to provide an identity, though I probably don't need it. But as Category doesn't support application, I'd still need a derived class anyway to add that operation.

答:
As you point out, the main problem with using Applicative here is that there is no sensible definition for pure. Hence, Apply was invented. At least, that's my understanding of it.

Unfortunately, I do not have examples on hand of instances of Apply that aren't also Applicative. It is claimed this is true for IntMap, but I have no idea why. Similarly, I don't know whether your example - offset integers - admits an Apply instance.


问:
Ext JS - open source license (GPL V3) on client and closed source on server - Does the server-side have to be open source in the end?
First, yes, I understand that you are not a lawyer and that you cannot give me legal advice. I swear I will not hold you accountable for any responses you may give, yada, yada, yada, etc, etc, etc.

Anyway...

Next, general details of my potential application:

Ext JS open source (GPL V3) app running all client-side code. THE CLIENT from here on.

ASP.NET MVC application running the server-side code. THE SERVER from here on.

3rd party / open-source / server-side framework for interfacing between previous two systems. THE INTERFACE from here on. Its licensing is highly permissive.

Is THE SERVER "contaminated" by the license of THE CLIENT?

There are a few variables to consider here:

Both THE SERVER and THE INTERFACE will be generating JSON to be directly used by THE CLIENT.

All systems are currently designed to be served from the same server, same IIS process; however, it would be easy enough to separate all server-side code and all client-side code.

Probably more (...?)

If you think that, "yes, given this arrangement of sub-systems, THE SERVER will have to be made available as GPL V3 code," would it be possible to completely separate the two by declaring THE CLIENT as an open source UI where 3rd party servers could be developed by whomever for whatever platform? In this case, I would just happen to be the developer of the first client, which happens to be an ASP.NET-based one?

Now a few specifics: I am an independent developer who would prefer to keep my options open. I currently have a 4.x commercial license for Sencha Ext JS, which was purchased at a very reasonable price. It is, at this point, out-dated; Ext JS 6.0.0 came out today after all. I do, however, refuse to purchase their licenses according to their new, absurd policies (e.g. 5 license minimum @ $4K-7K) plus support subscriptions to get their bug fixes!

Any thoughts? Well, besides, "ditch Sencha."

答:
IANAL, but as far as I understand you have nothing to worry about:

Copyleft only transfers to Derivative Work - that is, a program that contains parts of the copyleft program. Dynamic linking is a legal gray area(RMS claims it transfers copyleft, others claims it doesn't, I don't know if it was ever discussed in court). I've never heard anyone claiming it can be transferred via interprocess communication.

Even if copyleft was transferable via interprocess communication(and it doesn't!), it would have been the other way around(server->client) because the server doesn't depend on the client but the client depend on the server.

Even if the server was GPL - it usually doesn't matter. Essentially, GPL says that if someone legally gets the executable they have the right to get the sources as well, and are allowed to freely modify and distribute the project. As long as you run the server on your own machines (or machines you hire. Or even a free hosting service!) you don't have to release the sources, because you are the only one with access to the binaries. The users served by the servers don't get that right because they can't get the binaries to begin with.


问:
Are using <<include>> and <<extend>> relationship in this use-case diagram actually same?
I am trying to draw a UML use-case diagram to model requirements for a software project.

The two requirements I have issue to model are:

TravelAgent creates a booking for a [old] client who is requesting a home.

When a new client wishes to make a booking, the TravelAgent register him/her to the system before doing the booking.

I have two approaches to model these requirements:

Modeling the first use-case as a sub-procedure of the second use-case (Figure 1).

Extending the first use-case (Figure 2).

Both approach imply that the first use-case could be perform independently, but when the second use-case is executed, the first one MUST be executed too.

Are they actually same and both correct?

P.S. As another question, since the NewClient converts to a Client after the registration, should I show the NewClient as subclass of Client or something?

Figure 1

Figure 2

答:
All that I've learned about INCLUDE and EXTENDS in UML diagrams is that include is something that it is required and extends is optional. In your case, it is supposed that the client already is registered and logged in the system. So, he doesn't need to do a register again. But the newClient has to be registered to create a booking. I think it could look like this:

But I'm not sure, once I'm also learning...
I hope it helps..
Good Luck!


答: If you want to take a class in high school to help with programming take Machine Shop or Automotive Tech ed. if you school offers it.  The methods of methodically taking something apart diagnosing along the way to figure out what the problem is or how it works will be far more useful as a practical programmer than anything else you could take (non math/programming related)</p>

Title: Does knowing Latin or other logical languages contribute to being a better programmer?

Body:
I'm currently studying Latin at school, and what I've learned is that it's a very logical language. I feel this has contributed to my programming ability, as it makes it my code easier to understand.

Is there any relation between knowledge of a very logical language such as Latin and the comprehension of code?


问:
What are the disadvantages of writing code before writing unit tests?
I have always seen the recommendation that we should first write unit tests and then start writing code. But I feel that going the other way is much more comfortable (for me) - write code and then the unit tests, because I feel we have much more clarity after we have written the actual code. If I write the code and then the tests, I may have to change my code a little bit to make it testable, even if I concentrate much on creating a testable design. On the other hand, if I write the tests and then the code, the tests will change pretty frequently as and when the code shapes up.

As I see a lot of recommendations to start writing tests and then move on to coding, what are the disadvantages if I do it the other way - write code and then the unit tests?

答:
When you write a test, how do you know it will detect a fail condition? The answer is "test the test". How you do that is to write the test first, see it fail, and only see it pass when the unit under test has been coded successfully (the red/green/refactor cycle mentioned in one of the other answers).

Writing the code first and then the test leaves open the question of whether the test would show an honest fail.

Remember that your tests express specification. If you have to revise your tests as your code "shapes up", it suggests that your specifications are changing. That may or may not be a good thing. It could mean that your understanding of the problem was not initially correct. On the other hand, it could mean that you're testing "how" the unit is doing its job rather than what it is supposed to be accomplishing.


问:
interpretation of the statement in java
I am confused over the interpretation of the following statement

```<code>Fruit x= new Fruit();
</code>```

My interpretation is that the new operator along with Fruit(); creates a new object somewhere in the memory.

Now x is a reference variable that points toward the object created and if I write Fruit x , does it only mean that a reference variable is created which points no where?

Can i also say that x keeps the memory location of the object?

答:
The statement Fruit x = new  Fruit(); creates a new object belonging to the class Fruit and x stores a reference to that object.

More specifically, when the computer executes this statement, it allocates memory to hold a new object of type Fruit. It calls a constructor, which can initialize the instance variable of the object as well as perform other tasks. A reference to the new object is returned as the value of the expression "new Fruit()".

Finally, the assignment statement stores the reference in the variable x. So, x can now be used to access the new object.

Title: interpretation of the statement in java


问:
Can I resolve an issue with SRP, SOC that prevents object initialization via constructor?
In OOP, I can populate (initialize) an object using constructor injection at object creation time, or setter injection, after creation time.

I like the idea of populating object at creation time via constructor, for object parameters that are essential to the object.  And use setter methods for things that are non-essential or secondary.

And all was well.

Until, I discovered DataMapper pattern.  In the pattern I

load up data from the database (data concern)

map schema colums to object parameters (mapping concern)

create/update/delete/return the object to its caller (object management concern)

I am quite content with DataMapper essentially being the manager for the object, thereby creating the object, loading data, and then populating that object.  If all 3 of the above concerns share the same function, there is no issue as they all seem to seamlessly integrate together.

Problem

The issue arises when I start separating concerns.  Namely, the mapping concern.  Mapping concern should only concern itself with taking the DB schema column names and copying data from DB resource object over to the new object's data field parameter variables.  For me it translates to this

accept a created object as input parameter

fill out the object from DB schema via the mapping (using setters for private vars, or directly if vars are public)

return the filled out object back to its caller.

I am thinking that mapping concern should not be creating the object.  This means, the mapping concern cannot use constructor initialization.

Question

What can I do to use separate the mapping concern and still use constructor initialization?

Possible Work-arounds

Use setter initialization methods only [abandon constructor initialization even when it's desired]

bundle two different concerns of managing the object (namely creating it [means ability to initialize it via constructor]) and schema-to-object mapping inside the same class. [abandon SRP]

Code Example

For clarity - see comments

class ProductDataMapper
{
    public function dataConcern($id)
    {
        $sql = "SELECT model as name FROM product where id = {$id}";
        $result = db_query($sql);
        $data = db_fetch_array($result);
        return $data;
    }

    public function mappingConcern($data)
    {
        //schema to property mapping (to separate concerns)
        $parameters = array();
        $parameters['name'] = $data['schema_column_name_in_db'];

        //In order to use constructor initialization, mapping concern
        //has to be the place to *create* the product (using new)
        //my question deals with separating 'object creation' from 'object mapping'

        //init via constructor - this is the *undesirable* concern for a mapper
        $product = new Product($parameters);

        //init via setters
        foreach ($data as $key => $value) {
            $setter = 'set' . ucfirst($key);
            $product->$setter($value);
        }
        return $product;
    }

    public function getProduct($productId)
    {
        $data = $this->dataConcern($productId);
        $product = $this->mappingConcern($data);
        return $product;
    }
}
```

Update

I am thinking that I can separate out object creation WITH mapping into a separate concern.

That concern will be Object-Creation-and-Schema-Mapping-To-Object-via-Constructor.

Namely, still not perfect, because there will be two mapper concerns

mapper that creates and initializes the object via constructor

mapper that uses setters to populate the object

答:
You are over-using SRP. Let's take a look at mappingConcern's creation-and-initialization version:

```<code>public function mappingConcern($data)
{
    $parameters = $data;

    $product = new Product($parameters);

    return $product;
}
</code>```

$parameters is the same as $data, and $product is returned immediately, so it can be translated to:

```<code>public function mappingConcern($data)
{
    return new Product($data);
}
</code>```

That's all your function does! Calling another function(the constructor)! Nothing else - no logic to choose the function, no preparation of arguments, no parsing of returned value, no nothing - just calling another function, passing the argument as is.

Why can't you do this directly from getProduct?

```<code>public function getProduct($productId)
{
    $data = $this->dataConcern($productId);
    return new Product($data);
}
</code>```

When you do it like this, the question of constructor vs setters seems silly, right? So, even if you do need a mappingConcern function(for polymorphism or whatever), why can't it do this simple, one command?

I think your problem is that you are diving too deep when trying to separate responsibilities and concerns. SRP and SoC refer to the interface, not to the implementation(implementation has other rules for separating stuff). That is, when you describe what a function does it should only do one thing, but when you describe how it does it you can describe multiple things. What mappingConcern does is not "create an object and map the data to it" - that's the implementation. What mappingConcern does is "convert the raw $data to an object". That's one thing, and complies to SRP and SoC.

Body:
You are over-using SRP. Let's take a look at mappingConcern's creation-and-initialization version:

public function mappingConcern($data)
{
    $parameters = $data;

    $product = new Product($parameters);

    return $product;
}

$parameters is the same as $data, and $product is returned immediately, so it can be translated to:

public function mappingConcern($data)
{
    return new Product($data);
}

That's all your function does! Calling another function(the constructor)! Nothing else - no logic to choose the function, no preparation of arguments, no parsing of returned value, no nothing - just calling another function, passing the argument as is.

Why can't you do this directly from getProduct?

public function getProduct($productId)
{
    $data = $this->dataConcern($productId);
    return new Product($data);
}

When you do it like this, the question of constructor vs setters seems silly, right? So, even if you do need a mappingConcern function(for polymorphism or whatever), why can't it do this simple, one command?

I think your problem is that you are diving too deep when trying to separate responsibilities and concerns. SRP and SoC refer to the interface, not to the implementation(implementation has other rules for separating stuff). That is, when you describe what a function does it should only do one thing, but when you describe how it does it you can describe multiple things. What mappingConcern does is not "create an object and map the data to it" - that's the implementation. What mappingConcern does is "convert the raw $data to an object". That's one thing, and complies to SRP and SoC.


答:
Maybe; I also had a similar thought that maybe knowing how to program helped me learn a second language.

This came about when I took a French class several years ago just before I went on my first trip to Paris. French certainly has its quirks, but programming is largely nouns and verbs just like language. I swear that when I deconstructed the lessons along programming lines, the language got to be much easier to learn. It's more than likely just conjecture on my part, and it could be my enthusiasm for the class and trip had as much to do with my picking it up so easily as anything.

Learning another language is a great mental exercise so keep at it, but as others have said, don't look too deep into this.


问:
Is there a problem holding large numbers of open socket connections for lengthy periods of time?
The application we have in mind is a relay server. The aim is to accept large numbers of incoming socket connections (at least thousands) that will stay open for lengthy periods (hours or maybe days). They will exchange modest quantities of data and they need reasonably low latency.

The technical design is straightfoward and we have a test implementation. Our preference is to use Windows hosting and .NET, because that's the technology we know. However, this kind of usage is well outside what we are familiar with.

The question is whether there are specific limits or constraints to be aware of that are inherent in or common to software that does this, and that we should allow for in our design and/or test for before a roll-out.

I found this question (Handling large amounts of sockets) and this link (http://www.metabrew.com/article/a-million-user-comet-application-with-mochiweb-part-1), which tend to suggest that our solution should work.

--

Commenters have suggested opening and closing ports, or using some kind of protocol, without suggesting how. The problem is that at any time a message might be relayed to an individual known destination with the expectation that it be received quickly (say 1 second at most, preferably sooner). The destination is (in general) behind a firewall with unknown properties, so cannot (in general) run a server or accept incoming connections. It can only make outgoing connections. We think it needs a persistent outgoing connection in order to receive packets at any time without notice. Alternative suggestions would be of interest, although strictly off topic for this question.

Other commenters have suggested there are OS limits, but not specified any. Assuming that this is some version of Windows server and some (perhaps large) amount of memory, are the limits likely to be a problem? Roughly what will they be? Is Windows a bad idea?

答:
Having provided firewall and VPN support for a couple of years now, I can tell you with confidence that applications which keep ports open for an extended period of time are not stable from both the local server perspective and the network point of entry perspective. It can also be a security risk (if that is a consideration in your case).

Leaving a persistent connection open on a server port can potentially cause an issue on the firewall as the NAT table accumulates entries, for example.

I personally recommend keeping your connected client numbers in the 200 to 250 range per server for persistent connections via TCP/IP where the data being sent and received requires minimal latency.

If you have the hardware to move to ATM (Asynchronous Transfer Mode), you can reconfigure your clients to listen only to their specific address, which will take a significant burden off of your servers (at the expense of the clients).  ATM should get you into the 300 to 350 active clients per server capacity.

To clarify, the solution to this issue is to put your server in a DMZ on the firewall to enhance access and use ATM connectivity with as many clients as possible.  Otherwise you are at the mercy of the remote network firewall and other intermediate intelligent routers.


问:
Creating an interface just to decouple from third party libraries
I'm currently developing the Authorization module on a framework of mine.

I have the following class so far:

```<code>public interface IAuthorizationManager<C>
       where C : AuthorizationConfiguration
{
    void Configure(C configuration);
}
</code>```

One of my implementations is going to be OAuth authentication.

For that I have created the following manager:

```<code>public class OAuthAuthorizationManager : IAuthorizationManager<OAuthConfiguration>
{
    private IOAuthAuthorizationServerProvider _authorizationProvider;
    private IAuthenticationTokenProvider _refreshTokenProvider;

    public AuthorizationManager(IOAuthAuthorizationServerProvider authorizationProvider,
                                IAuthenticationTokenProvider refreshTokenProvider)
    {
        this._authorizationProvider = authorizationProvider;
        this._refreshTokenProvider = refreshTokenProvider;
    }

    public void Configure(OAuthConfiguration configuration)
    {
       configuration.Application.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions() {
             AllowInsecureHttp = !configuration.IsSecure,
             TokenEndpointPath = new PathString(configuration.TokenEndpoint),
             AccessTokenExpireTimeSpan = configuration.TokenExpiration,
             Provider = _authorizationProvider,
             RefreshTokenProvider = _refreshTokenProvider
       });
       configuration.Application.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}
</code>```

Now, here's the thing, the implementations of IOAuthAuthorizationServerProvider and IAuthenticationTokenProvider are going to be injected through the constructor.

I am using Ninject for dependency injection.

In my application's startup project I have the following module:

```<code>public class AuthorizationModule : ApplicationModule
{
      public override void Load()
      {
          Kernel.Bind<IOAuthAuthorizationServerProvider>().To<AuthorizationProvider<User, Client>>();
          Kernel.Bind<IAuthenticationTokenProvider>().To<RefreshTokenProvider<RefreshToken>();

          Kernel.Bind<IAuthorizationManager<OAuthConfiguration>>().To<OAuthAuthorizationManager>();
      }
}
</code>```

The problem is that the interfaces IOAuthAuthorizationServerProvider and IAuthenticationTokenProvider are part of the Owin.Security.OAuth library, so when I am configuring the injection, my application's startup project needs to directly reference this library and its dependencies. This pollutes my packages.config. I don't like the idea to have the same library referenced twice in my solution, when only one project actually uses it.

AuthorizationProvider<User, Client> and RefreshTokenProvider<RefreshToken> are classes of mine, so there's no problem with those.

I was thinking of maybe creating an interface like this (of course i'd chose another name):

```<code>public class IMyOAuthAuthorizationServerProvider : IOAuthAuthorizationServerProvider { }

public class IMyAuthenticationTokenProvider : IAuthenticationTokenProvider { }
</code>```

Along with the associated changes:

```<code>public AuthorizationManager(IMyOAuthAuthorizationServerProvider authorizationProvider, IMyAuthenticationTokenProvider refreshTokenProvider)
{
    this._authorizationProvider = authorizationProvider;
    this._refreshTokenProvider = refreshTokenProvider;
}
</code>```

And:

```<code>Kernel.Bind<IMyOAuthAuthorizationServerProvider>().To<AuthorizationProvider<User, Client>>();
Kernel.Bind<IMyAuthenticationTokenProvider>().To<RefreshTokenProvider<RefreshToken>>();
</code>```

Of course the Owin.Security.OAuth will keep being referenced, but this time indirectly, therefore I don't need to install them (via NuGet) on my main project.

I wanted to know if this is a common practice, what are the disadvantages of this approach, and any tips or alternative solution would be highly (and gladly) accepted.

答:
Does Ninject provide a configuration-file based approach (like here)? I think if you did that the type would be dynamically loaded, and voila! - no dependency in your project.

The drawback is that now you have potential runtime failures rather than compile-time ones, but I think that's what you would rather have in your situation.


问:
Java: using final keyword only on method parameters that expect immutable objects?
I came across the interesting topic about final method parameters and that they essentially don't provide much advantages. I wondered if it would be sensible to mark only those method parameters as final, when it is advisable to pass an immutable object.

I don't know if this might mislead some people when they're reading the code, because final does not provide this immutability, and even the compiler wouldn't understand that I would like an immutable object to be passed to this method param. But it would be sth like a "human-readable" indicator (especially in APIs) that passing an immutable object is advised.

How would such a concept be evaluated by experienced java programmers?

答:
Personally, I used to use final always (these days, from-time-to-time) only to ensure variables are not being re-assigned; nothing more, nothing less.

The advantage of not reassigning variables is important to me actually, as it discourages the 'crutch' of temporary variables. This in turn encourages me to re-inspect my code for repetitive code (replacing them with inlined methods, or even to re-structure them) and eliminates potential bugs due to careless re-assignments.

The latter is more helpful in long do-it-all methods, but once broken down into smaller methods, it's easier to see the scope of variables and therefore also to less likely to re-assign them in the first place. Hence my personal preference to use them lesser now.

To address your concern about accepting mutable/immutable objects, my suggestion is to make one the default approach for your library/codebase, stick with that and then document the exception. In other words, if it's better code-wise to be passing immutable objects by default, then you can make that clear so from 'Getting Started'-kind of documentation to address this codebase-wide. You can then make use of @assylias's suggestion to document the methods to say something like:

```<code>/**
 *  This method works with mutable arguments as well.
 */
</code>```

Or

```<code>/**
 *  The side-effect of this method modifies the mutable arguments.
 */
</code>```

You can also play with your classes name by calling them MyImmutableType (for example). I generally avoid this as their names don't 'roll well', but YMMV.

```<code>// this has to return a new MyImmutableType instance
public MyImmutableType doSomething(MyImmutableType input);

// this possibly mutates the mutable argument, which the caller will then use
public void doSomething(MyMutableType input);
</code>```

Perhaps more importantly, final your arguments' classes too so that if callers/users of your codebase decide to check your source code, then can also immediately tell that the class is immutable.

```<code>public final class Wrapper<T> {
    private final int id;
    private final T payload;

    public Wrapper(int id, T payload) {
        this.id = id;
        this.payload = payload;
    }
}
</code>```

In conclusion, if I see a final keyword in the method signature, all I know is that the developer is doing something right by not (potentially) reassigning method arguments within the method. It should not be relied upon to indicate whether arguments should/must be be immutable.

Body:
Personally, I used to use final always (these days, from-time-to-time) only to ensure variables are not being re-assigned; nothing more, nothing less.

The advantage of not reassigning variables is important to me actually, as it discourages the 'crutch' of temporary variables. This in turn encourages me to re-inspect my code for repetitive code (replacing them with inlined methods, or even to re-structure them) and eliminates potential bugs due to careless re-assignments.

The latter is more helpful in long do-it-all methods, but once broken down into smaller methods, it's easier to see the scope of variables and therefore also to less likely to re-assign them in the first place. Hence my personal preference to use them lesser now.

To address your concern about accepting mutable/immutable objects, my suggestion is to make one the default approach for your library/codebase, stick with that and then document the exception. In other words, if it's better code-wise to be passing immutable objects by default, then you can make that clear so from 'Getting Started'-kind of documentation to address this codebase-wide. You can then make use of @assylias's suggestion to document the methods to say something like:

/**
 *  This method works with mutable arguments as well.
 */

Or

/**
 *  The side-effect of this method modifies the mutable arguments.
 */

You can also play with your classes name by calling them MyImmutableType (for example). I generally avoid this as their names don't 'roll well', but YMMV.

// this has to return a new MyImmutableType instance
public MyImmutableType doSomething(MyImmutableType input);

// this possibly mutates the mutable argument, which the caller will then use
public void doSomething(MyMutableType input);

Perhaps more importantly, final your arguments' classes too so that if callers/users of your codebase decide to check your source code, then can also immediately tell that the class is immutable.

public final class Wrapper<T> {
    private final int id;
    private final T payload;

    public Wrapper(int id, T payload) {
        this.id = id;
        this.payload = payload;
    }
}

In conclusion, if I see a final keyword in the method signature, all I know is that the developer is doing something right by not (potentially) reassigning method arguments within the method. It should not be relied upon to indicate whether arguments should/must be be immutable.


问:
What is REST (in simple English)
Lately I have become interested in familiarizing myself with REST. I tried reading wiki entry on REST, but it was of no help. I would really appreciate it if someone can explain in simple English (that is without unnecessary tech jargon)

What is REST?

What position it occupies in web architecture ecosystem?

How tightly (or loosely) it is coupled with protocol?

What are the alternatives to REST and how does REST compare with them?

I understand it may not be possible to answer this in one or two paragraphs, in that case relevant links will be highly appreciated.

答:
What is REST (in simple English)

Plain English:

REpresentational: the action of speaking or acting on behalf of someone.

State Transfer: transfer status.

Technical:

REST is the way HTTP should be used.

we do not transfer an actual object but a representation of it in a form (eg. a xml/json/text to represent a database table).

RESTs for exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

REST is representes via some media type. Some examples of media types include XML, JSON, and RDF.

REST is an architectural style for resource-oriented architecture (ROA), not a spec or a standard.

Everything is identified by unique endpoint. i.e. There is one endpoint for each resource(data).

Endpoint is consist of domain name with resource address.

REST vs SOAP

Title: What is REST (in simple English)

ContentLicense: CC BY-SA 4.0


问:
Is testable code better code?
I'm attempting to get into the habit of writing unit tests regularly with my code, but I've read that first it's important to write testable code.
This question touches on SOLID principles of writing testable code, but I want to know if those design principles are beneficial (or at least not harmful) without planning on writing tests at all. To clarify - I understand the importance of writing tests; this is not a question on their usefulness.

To illustrate my confusion, in the piece that inspired this question, the writer gives an example of a function that checks the current time, and returns some value depending on the time. The author points to this as bad code because it produces the data (the time) it uses internally, thus making it difficult to test. To me, though, it seems like overkill to pass in the time as an argument. At some point the value needs to be initialized, and why not closest to consumption? Plus, the purpose of the method in my mind is to return some value based on the current time, by making it a parameter you imply that this purpose can/should be changed. This, and other questions, lead me to wonder if testable code was synonymous with "better" code.

Is writing testable code still good practice even in the absence of tests?

Is testable code actually more stable? has been suggested as a duplicate. However, that question is about the "stability" of the code, but I am asking more broadly about whether the code is superior for other reasons as well, such as readability, performance, coupling, and so forth.

答:
Writing testable code is important if you want to be able to prove that your code actually works.

I tend to agree with the negative sentiments about warping your code into heinous contortions just to fit it to a particular test framework.

On the other hand, everybody here has, at some point or other, had to deal with that 1,000 line long magic function that is just heinous to have to deal with, virtually can't be touched without breaking one or more obscure, non-obvious dependencies somewhere else (or somewhere within itself, where the dependency is nearly impossible to visualize) and is pretty much by definition untestable. The notion (which is not without merit) that testing frameworks have become overblown should not be taken as a free license to write poor quality, untestable code, in my opinion.

Test-driven development ideals do tend to push you toward writing single-responsibility procedures, for example, and that is definitely a good thing. Personally, I say buy into single-responsibility, single source of truth, controlled scope (no freakin' global variables) and keep brittle dependencies to a minimum, and your code will be testable. Testable by some specific testing framework? Who knows. But then maybe it's the testing framework that needs to adjust itself to good code, and not the other way around.

But just to be clear, code that is so clever, or so long and/or interdependent that it is not easily comprehended by another human being is not good code. And it also, coincidentally, isn't code that can easily be tested.

So nearing my summary, is testable code better code?

I don't know, maybe not. People here have some valid points.

But I do believe that better code tends to also be testable code.

And that if you're talking about serious software for use in serious endeavors, shipping untested code is not the most responsible thing you could be doing with your employer's or your customers' money.

It's also true that some code requires more rigorous testing than other code and it's a little silly to pretend otherwise. How would you like to have been an astronaut on the space shuttle if the menu system that interfaced you with the vital systems on the shuttle wasn't tested? Or an employee at a nuclear plant where the software systems monitoring temperature in the reactor weren't tested? On the other hand, does a bit of code generating a simple read-only report require a container-truck full of documentation and a thousand unit tests? I sure hope not. Just saying...

Title: Is testable code better code?


答:
I'm currently studying Latin at school, and what I've learned is that it's a very logical language, unlike, e.g. English. To me, I think this has contributed to my programming ability—it makes it easier for me to understand my code.

Don't overthink things.

Have any of you studied Latin (or another very logical language), and if so, do you also feel it helped you as a programmer?

Studied? Yes.

Helped me in my programming issues? No, not at all.


问:
Would it be possible to create a language similar to Ruby/Python with static typing that had the speed/memory usage of a compiled C program?
One of the main drawbacks of Ruby/Python is performance. I understand that they are interpreted and C is compiled. (And there are things like JRuby which do JIT compilation with Ruby). But they never manage to get the same speed/memory usage as a compiled program. Would it be possible to create a new language that had the same syntax as Ruby for example (with one change: static typing) that compiled down to something as fast as a C program?

I'm trying to think of what other differences there are other than static typing than prevent you from getting the same speed. (Maybe allocating buffers of a fixed size as opposed to an abstraction which handles this for you). But it seems like you could get pretty close?

If so, why has no one created a compiled version of Ruby/Python with static typing?

答:
Performance doesn't always come down to interpreted vs. compiled.  There are so many other factors that can influence the performance equation:

The nature of the software can favor programmer productivity over clock cycles.

Other factors are more important, like network and database latency.

Compilation and interpretation are a gray area anyway.  Is a JIT interpreted or compiled?

Byte code and certain programming language constructs can make optimizations possible that wouldn't otherwise be available.


答: Cython and Numba are examples of what this would look like for Python, and yes, you can get performance comparable to C code. Cython is an extension of the Python language that adds type annotations and makes it easy to call C functions. Numba uses hints provided as Python @decorators to inform it of the data types for which it will generate efficient vectorized C code, and will raise an error if the resulting function is called with incorrectly typed arguments.</p>

Title: Would it be possible to create a language similar to Ruby/Python with static typing that had the speed/memory usage of a compiled C program?

Body:
One of the main drawbacks of Ruby/Python is performance. I understand that they are interpreted and C is compiled. (And there are things like JRuby which do JIT compilation with Ruby). But they never manage to get the same speed/memory usage as a compiled program. Would it be possible to create a new language that had the same syntax as Ruby for example (with one change: static typing) that compiled down to something as fast as a C program?

I'm trying to think of what other differences there are other than static typing than prevent you from getting the same speed. (Maybe allocating buffers of a fixed size as opposed to an abstraction which handles this for you). But it seems like you could get pretty close?

If so, why has no one created a compiled version of Ruby/Python with static typing?


答:
From my experience, one of the most important and most far-reaching decisions you make when building a program is how you break the code down into units (where "units" is used in its broadest sense). If you are using a class-based OO language, you need to break all the internal mechanisms used to implement the program into some number of classes. Then you need to break each class' code into some number of methods. In some languages, the choice is how to break your code into functions. Or if you do the SOA thing, you need to decide how many services you will build and what will go into each service.

The breakdown which you choose has an enormous effect on the whole process. Good choices make the code easier to write, and result in fewer bugs (even before you start testing and debugging). They make it easier to change and maintain. Interestingly, it turns out that once you find a good breakdown, it is usually also easier to test than a poor one.

Why is this so? I don't think I can understand and explain all the reasons. But one reason is that a good breakdown invariably means choosing a moderate "grain size" for units of implementation. You don't want to cram too much functionality and too much logic into a single class/method/function/module/etc. This makes your code easier to read and easier to write, but it also makes it easier to test.

It's not just that, though. A good internal design means that the expected behavior (inputs/outputs/etc) of each unit of implementation can be defined clearly and precisely. This is important for testing. A good design usually means that each unit of implementation will have a moderate number of dependencies on the others. That makes your code easier for others to read and understand, but also makes it easier to test. The reasons go on; maybe others can articulate more reasons which I can't.

With regard to the example in your question, I don't think that "good code design" is equivalent to saying that all external dependencies (such as a dependency on the system clock) should always be "injected". That might be a good idea, but it is a separate issue from what I am describing here and I won't delve into its pros and cons.

Incidentally, even if you make direct calls to system functions which return the current time, act on the filesystem, and so on, this does not mean you can't unit-test your code in isolation. The trick is to use a special version of the standard libraries which allows you to fake the return values of system functions. I've never seen others mention this technique, but it is fairly simple to do with many languages and development platforms. (Hopefully your language runtime is open-source and easy to build. If executing your code involves a link step, hopefully it is also easy to control which libraries it is linked against.)

In summary, testable code is not necessarily "good" code, but "good" code is usually testable.

Title: Is testable code better code?

Body:
I'm attempting to get into the habit of writing unit tests regularly with my code, but I've read that first it's important to write testable code.
This question touches on SOLID principles of writing testable code, but I want to know if those design principles are beneficial (or at least not harmful) without planning on writing tests at all. To clarify - I understand the importance of writing tests; this is not a question on their usefulness.

To illustrate my confusion, in the piece that inspired this question, the writer gives an example of a function that checks the current time, and returns some value depending on the time. The author points to this as bad code because it produces the data (the time) it uses internally, thus making it difficult to test. To me, though, it seems like overkill to pass in the time as an argument. At some point the value needs to be initialized, and why not closest to consumption? Plus, the purpose of the method in my mind is to return some value based on the current time, by making it a parameter you imply that this purpose can/should be changed. This, and other questions, lead me to wonder if testable code was synonymous with "better" code.

Is writing testable code still good practice even in the absence of tests?

Is testable code actually more stable? has been suggested as a duplicate. However, that question is about the "stability" of the code, but I am asking more broadly about whether the code is superior for other reasons as well, such as readability, performance, coupling, and so forth.


答:
Just adding explicit type annotations to Ruby wouldn't do the trick. One key characteristic of Ruby is that any method can be redefined at runtime. So even if you know that some value will always be an instance of class C, that doesn't allow you to do things like inlining.

Note that in Ruby, even loops are actually implemented as method calls. So your compiler couldn't even assume that a loop is... actually a loop, since #each could be redefined at runtime.

You could design a language with "Ruby syntax", but take away all the runtime metaprogramming. That could be compiled to efficient machine code, but it wouldn't be Ruby. The key characteristic which makes Ruby what it is, is the extreme flexibility to modify almost everything dynamically, at runtime.

You could conceivably write an incredibly sophisticated compiler which would do global analysis of an entire program, and determine whether any of those "dynamic" features are actually used or not. In many cases, this would practically require something close to "strong AI". Not practical.

Another option, which has been done with other languages and could be done in Ruby, would be to write a JIT compiler which does optimizations like inlining based on the assumption that the current class and method definitions won't change, and backs out of those optimizations if they do. That is the way to make Ruby code very, very fast. Unfortunately, nobody has done it yet.


问:
How much can you detect undefined behaviour using testing
I hope this question fits this site.
You may know you can't detect undefined behaviour in C using compilers - and some tools (static analysis) can help you detect it.
My question is more empirical - I know exact solution cant' exist.
Question:

Say one developed software and performed intensive testing of the application for several days and no issues found, how much can he be sure there is no undefined behaviour constructs used in his application?

Consider same situation as above and that the software the programmer developed has been deployed to a company who is using it for several months and no issues have been reported. In practice, how much can one be sure in such case the there is no Undefined behaviour in software?

PS. Extra: If there is undefined behaviour in function A() in program, can program behave well when it reaches A() and malfunction when it reaches function B() - which has no problems?

答:
It is hard to say. Like any other bug, it can work for years, until one day your application starts crashing, after aparently innocent change.

One such example is writing buffer after it's end.

That is why the software needs to be tested at various levels (unit, functional, integration, etc), checked with static analisys tools, and those tests should be executed with memory checkers (like valgrind, when possible). Then you can say that you extended your safety net, and that the probability for bug (including undefined behaviours) is reduced.

If there is undefined behaviour in function A() in program, can program behave well when it reaches A() and malfunction when it reaches function B() - which has no problems?

With undefined behaviour anything is possible, including the nasal demons.

As I said above, even a simple change can cause UB to misbehave in very bad ways. To make things worse, it doesn't have to trigger the same behaviour every time. It can appear to work in 99 execution, and crash your application
on the 100th.


问:
Is login a use-case for a user of a system?
I've been researching since my last project last semester and I haven't found a definitive answer for this question. Now I've got one more project to draw a Use-Case diagram and I'm still confused about it.

In the end, can I create a Login Use-Case or not?

Because in my project the user must be logged in to access his informations.

I know I can be repeating this question, but no one and nowhere has a consistent answer ☹

Here is an example how I have it in mind:

If anybody can demystify this mistery, it would be great! Because I've been visiting many websites and forums (even here) and I can not find a consistent answer.

答:
Yes, it is valid to have a Login use-case.

Having a separate Login use-case is especially useful if the login action is something that the user can do as a stand-alone action (for example, I can login to SO and then decide to view my profile or to post a question or do something else).

What you can't really do is show in a use-case diagram, like the one you have, that the Login use-case is a precondition for the View Profile use-case. This dependency is best expressed in the textual description of each use-case.


问:
Python Classes and Design Questions
What is the best way to design a class to see if an update occurs on a property?

I have a whole bunch of classes, and current am going through a re-design of the python package I created.  Essentially what I do is take the values of a REST service description, and put them into a class along with the functions that can operate on that service.

I have a bunch of design questions:

Can I have a bunch of base classes like: Map Service, Feature Service where the functions are defined, but not the properties and create classes on the fly? Is that possible or recommended?  Right now I have everything defined for each service type, but I'm trying to see if there is a way to shrink my code base.

Should I use the get/set properties to track changes and just have a variable called isChanged default set to False and when one property is changed, then change it to True, or is there another way to do this?  This relates back to question #1.  If I do this by defining each property, then I need a different way to track class changes.

Since the operations function on web services, should I make them asynchronous and support callback functions?  Can anyone provide samples/guidelines on how to properly design a class to support this?

My classes all inherit from object, thus allowing the use of the get/set notation. Example: @property

Thank you for any insight you may provide.

答:
You could create @property decorated functions. In the setter one, you make sure you have something that calls all the pre-defined callback for said property. This is a visitor pattern really.

So, in untested and incomplete code, something akin to this:

```<code>@ook.setter
def ook(self, value):
    self._whatever = ook
    for func in self._ook_callbacks:
        func(self_whatever)
</code>```

Title: Python Classes and Design Questions

Body:
You could create @property decorated functions. In the setter one, you make sure you have something that calls all the pre-defined callback for said property. This is a visitor pattern really.

So, in untested and incomplete code, something akin to this:

@ook.setter
def ook(self, value):
    self._whatever = ook
    for func in self._ook_callbacks:
        func(self_whatever)


问:
Does it ever make sense to read from and/or write to a bound, listening socket?
I'm experimenting a little with creating a socket server, in PHP. In doing so I'm trying to abstract away the kinds of sockets I think I'll be needing, that I've tentitively named:

ListenSocket — the 'master' socket, that is bound to an address/port and listens for and accepts incoming connections.

CommunicationSocket — a 'child' socket, that represents an accepted, incoming connection, which the server will communicate with.

As the name already kind of implies, I will only define read() and write() type of methods on the CommunicationSocket.

However, doing so got me wondering: does it ever make sense to read from or write to the first type of socket (the bound, listening type)?

答:
I interpret your question in a way that you refer to TCP/IP sockets. With UDP/IP sockets it is different.

Two scenarios:

Scenario 1: 1. bind 2. connect 3. listen

Result: You cannot listen at a connected socket.

```<code>>>> import socket
>>> s = socket.socket()
>>> s.bind(('', 0))
>>> s.send(b'a')
Traceback (most recent call last):
  File "<pyshell#130>", line 1, in <module>
    s.send(b'a')
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
>>> s.connect(('google.de', 80))
>>> s.listen(1)
Traceback (most recent call last):
  File "<pyshell#132>", line 1, in <module>
    s.listen(1)
OSError: [WinError 10056] A connect request was made on an already connected socket
</code>```

Scenario 2: 1. bind 2. listen 3. connect

Result: You can not connect or send at a listening socket.

```<code>>>> s = socket.socket()
>>> s.bind(('', 0))
>>> s.listen(1)
>>> s.connect(('google.de', 80))
Traceback (most recent call last):
  File "<pyshell#136>", line 1, in <module>
    s.connect(('google.de', 80))
OSError: [WinError 10022] An invalid argument was supplied
>>> s.send(b"123")
Traceback (most recent call last):
  File "<pyshell#137>", line 1, in <module>
    s.send(b"123")
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
</code>```

Body:
I interpret your question in a way that you refer to TCP/IP sockets. With UDP/IP sockets it is different.

Two scenarios:

Scenario 1: 1. bind 2. connect 3. listen

Result: You cannot listen at a connected socket.

>>> import socket
>>> s = socket.socket()
>>> s.bind(('', 0))
>>> s.send(b'a')
Traceback (most recent call last):
  File "<pyshell#130>", line 1, in <module>
    s.send(b'a')
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
>>> s.connect(('google.de', 80))
>>> s.listen(1)
Traceback (most recent call last):
  File "<pyshell#132>", line 1, in <module>
    s.listen(1)
OSError: [WinError 10056] A connect request was made on an already connected socket

Scenario 2: 1. bind 2. listen 3. connect

Result: You can not connect or send at a listening socket.

>>> s = socket.socket()
>>> s.bind(('', 0))
>>> s.listen(1)
>>> s.connect(('google.de', 80))
Traceback (most recent call last):
  File "<pyshell#136>", line 1, in <module>
    s.connect(('google.de', 80))
OSError: [WinError 10022] An invalid argument was supplied
>>> s.send(b"123")
Traceback (most recent call last):
  File "<pyshell#137>", line 1, in <module>
    s.send(b"123")
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied


问:
Is a number used only once and directly bound to a function parameter a magic number?
I want to avoid numbers used directly in expressions without obvious meaning. However, if a number is used only once, as an argument passed into a function, and that number can be easily changed without breaking the program, is that number considered a magic number?

For example, I have a function double doSimulation(double alpha, double beta, unsigned count) where the parameters are to the simulation model. In my application code, I type in double x = doSimulation(0.5, 0.2, 100) as part of the application logic, where the numbers 0.5, 0.2 and 100 are prone to change and not used anywhere else, i.e. they can be changed directly to improve the model.

In this case, are the numbers considered magic numbers? Is it redundant to declare

```<code>const double ALPHA = 0.5;
const double BETA = 0.5;
const unsigned COUNT = 100;
</code>```

and use them only once, as the numbers are already named by means of function parameter?

答:
Yes, they still are. The point behind the 'magic number' concept is that they are meaningless by themselves. What does 0.5 mean? Once you give it a variable name, you've turned that value into a thing with meaning. It also helps to edit or update them, if you know all your magic numbers are held in a certain place (eg at the top of your class/header/etc) then you can change the value confident that its being changed in the right place.

That you can also be confident its changed consistently across you program if (or when) it gets used multiple times is a bonus.

The only time not to use a variable to define these is if the value never changes, is a constant and is not going to ever change. There's no need to write 100 as a constant when its used for calculating percentages.


答:
In both cases, testing will provide 0% additional certainty that no undefined behavior constructs are used in the application. Testing inherently does not have the ability to detect undefined behavior. Testing tests for wrong behavior. Undefined is very different from wrong.

"Undefined behavior constructs" are often deterministic (meaning we can know what happens, and always the same thing happens) if run in a well specified environment. Many types of undefined behavior work similar to the following: The program writes to a variable that it shouldn't write to, that variable is never read afterwards, and the program works correctly. From the perspective of the external test, there is no issue. Undefined behavior that gives a wrong result also exists, but is usually detected and fixed quickly, because the wrong result makes it easy to spot.

Such "harmless" undefined behavior is still seriously dangerous, because it relies on the aforementioned well specified environment. Over the lifetime of a program, there are often some minor and some major changes to that well specified environment. Some of these changes are compiler changes, OS updates, change of CPU architecture (the results of going from multi-threaded single core to multi-threaded multi-core were particularly nasty).

Title: How much can you detect undefined behaviour using testing

Body:
I hope this question fits this site.
You may know you can't detect undefined behaviour in C using compilers - and some tools (static analysis) can help you detect it.
My question is more empirical - I know exact solution cant' exist.
Question:

Say one developed software and performed intensive testing of the application for several days and no issues found, how much can he be sure there is no undefined behaviour constructs used in his application?

Consider same situation as above and that the software the programmer developed has been deployed to a company who is using it for several months and no issues have been reported. In practice, how much can one be sure in such case the there is no Undefined behaviour in software?

PS. Extra: If there is undefined behaviour in function A() in program, can program behave well when it reaches A() and malfunction when it reaches function B() - which has no problems?


问:
Guideline/best practices on what traits/categories to give to tests
Is there any standard on what traits/categories to give to tests?

Here is an example:

using Xuint;

public class XUnitTest1
{
    [Fact]
    [Trait("Category", "CI")]
    public void TestMethodX1() { ... }

    [Fact]
    [Trait("Category", "CI")]
    public void TestMethodX2() { ... }

    [Fact]
    [Trait("Category", "CI")]
    [Trait("Runningtime", "Short")]
    [Trait("Priority", "2")]
    [Trait("Owner", "Terje")]
    public void TestMethodX3()
    {
        var sut = new SomeClasses.VerySimpleMath();
        int result = sut.Add(2, 3);
        Assert.Equal(result, 5)
    }
}
```

I guess that this is mostly used to reduce the time of executing when some are long but is there any standard? Should one bother starting giving traits/categories right from the start or only when tests are taking longer to run or when the need arises? What kind or traits/categories do people usually end up with?

答:
You may want to use traits for

Selectively running tests. For example, I use an Integration trait so that my dev machine test runner doesn't constantly try to run DB tests. You could also perhaps use a Nonessential trait to mark that if a test fails it won't stop the build from passing

Metrics, so that you can (at a glance) see how many test are covering a particular module, how many of those are integration tests, etc


答:
Many seemingly reasonable things in C (and C++) actually have undefined behavior and this is a common source of bugs in programs.

Moreover there is no good way to determine whether a large scale application is free of undefined behavior and thus not susceptible to breaking in the future.

Some techniques like Undefined Behavior Coverage (see also the Klee project that uses symbolic analysis to try every possible path) have been proposed but they don't quantify the "security level".

There are many good tools:

Valgrind memcheck (can't find things the optimizer removes)

clang -fcatch-undefined-behavior that inserts runtime checks to find violations

c-semantic-tools (see An Executable Semantics For C Is Useful for an introduction)

clang static analizer

...

but nothing that gives full confidence that your code won't break in the future (or at least a security index).

The best you can do is be very careful, use good tools and hope for the best.

Some other interesting / related link are:

What Every C Programmer Should Know About Undefined Behavior  (especially part 2 and 3)

A C++ implementation that detects undefined behavior?