问:
Do I need to publish deployment scripts for deploying AGPL licensed work (MongoDB)
MongoDB is dual-licensed with AGPL (the engine) and ASL 2.0 (the drivers). In a nutshell, merely using MongoDB through the drivers does not dictate to release your source code (due to drivers' ASL 2.0 license).

AFAIK, only if you directly call the mongo engine, you need to give out your code that's using it (but still not the application code that talks to mongo via the drivers).

Check this MongoDB blog entry: http://blog.mongodb.org/post/103832439/the-agpl

What if you deploy (install, configure) mongodb in your deployment scripts. And then start/stop/restart those processes. And then maybe create some users via mongo shell. Do you need to publish your deployment scripts?

(A bonus question: how can they publish the drivers as ASL 2.0 if those drivers use the AGPL-licensed part of MongoDB over the network? Because they are authors of both?)

答:
Cue the usual "I'm not a lawyer" disclaimer.

This saying, GPL licenses aim to protect the users right to study the code of a piece of software, even if modified and redistributed. AGPL adds another channel of "redistribution" by explicitly stating that exposing the software to use through network systems entails the same consequences as redistributing it.

In your case, however, you are NOT modifying the MongoDB software. You merely creating related, but distinct, works that happen to interact with MongoDB. Just like a web application which uses Mongo as its storage engine, your deployment script are therefore NOT required to be published.

Relevant quote from the linked blog post is here:

The copyleft applies only to the mongod and mongos database programs.

You aren't modifying either of those two programs, so the copyleft doesn't apply.


问:
How are design-by-contract and property-based testing (QuickCheck) related?
Is their only similarity the fact that they are not xUnit (or more precisely, not based on enumerating specific test cases), or is it deeper than that?

Property-based testing (using QuickCheck, ScalaCheck, etc) seem well-suited to a functional programming style where side-effects are avoided. On the other hand, Design by Contract (as implemented in Eiffel) is more suited to OOP languages: you can express post-conditions about the effects of methods, not just their return values.

But both of them involve testing assertions that are true in general (rather than assertions that should be true for a specific test case). And both can be tested using randomly generated inputs (with QuickCheck this is the only way, whereas with Eiffel I believe it is an optional feature of the AutoTest tool).

Is there an umbrella term to encompass both approaches? Or am I imagining a relationship that doesn't really exist.

答:
Maybe one relationship lies in the concept of Oracle described by Bertrand Meyer, author of Eiffel, in "Seven Principles of Software Testing".

A test run is only useful if you can unambiguously determine whether
  it passed. The criterion is called a test oracle. If you have a few
  dozen or perhaps a few hundred tests, you might afford to examine the
  results individually, but this does not scale up. The task cries for
  automation.

Principle 4: Applying oracle
  Determining success or failure of tests must be an automatic process.

This statement of the principle leaves open the form of oracles.
  Often, oracles are specified separately. In research such as ours,
  they are built in, as the target software already includes contracts
  that the tests use as oracles.

Principle 4 (variant): Contracts as oracles
  Oracles should be part of the program text, as contracts. Determining test success or failure should be an automatic process consisting of
  monitoring contract satisfaction during execution.

Based on this, I guess we could say QuickCheck and Eiffel's Auto Test both use automated test oracles but different oracle forms, the former being external to the production program (properties expressed in separate test suite) and the latter, built into the production program (contracts).

From a historical perspective, we can assume that QuickCheck (first released in 1999) and earlier work on property-based testing dating back to the 90's served as inspiration to Eiffel's AutoTest (which appeared in 2008), although I couldn't find any firm evidence of that in Bertrand Meyer's papers or interviews.

ContentLicense: CC BY-SA 3.0


问:
How to design an IDisposable that unconditionally needs to be disposed?
Consider a class that implements IDisposable, and that has members in such a way that it will never become eligible for garbage collection when it is not disposed. And as it will not be garbage collected, it will not have the chance to use the destructor for cleaning up.

As a result, when it is not disposed (e.g. unreliable users, programming errors), resources will be leaked.

Is there a general approach how such a class can be designed to deal with such a situation or to avoid it?

Example:

```<code>using System;

class Program
{
    static void Main(string[] args)
    {
        new Cyclical();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.ReadKey();
    }
}

class Cyclical
{
    public Cyclical()
    {
        timer = new System.Threading.Timer(Callback, null, 0, 1000);
    }

    System.Threading.Timer timer;

    void Callback(object state)
    {
        Console.Write('.');  // do something useful
    }

    ~Cyclical()
    {
        Console.WriteLine("destructor");
    }
}
</code>```

(Omitted IDisposable to keep example short.) This class uses a Timer to do something useful at certain intervals. It needs a reference to the Timer to avoid it is garbage collected.

Let’s assume the user of that class will not dispose it. As a result of the timer, somewhere some worker thread has a reference to the Cyclical instance via the callback, and as a result, the Cyclical instance will never become eligible for garbage collection, and its destructor will never run, and resources will leak.

In this example, a possible fix (or workaround) could be to use a helper class that receives callbacks from the Timer, and that does not have a reference, but only a WeakReference to the Cyclical instance, which it calls using that WeakReference.

However, in general, is there a design rule for classes like this that need to be disposed to avoid leaking resources?

For the sake of completeness, here the example including IDispose and including a workaround/solution (and with a hopefully less distracting name):

```<code>class SomethingWithTimer : IDisposable
{
   public SomethingWithTimer()
   {
      timer = new System.Threading.Timer(StaticCallback,
         new WeakReference<SomethingWithTimer>(this), 0, 1000);
   }

   System.Threading.Timer timer;

   static void StaticCallback(object state)
   {
      WeakReference<SomethingWithTimer> instanceRef
         = (WeakReference<SomethingWithTimer>) state;
      SomethingWithTimer instance;
      if (instanceRef.TryGetTarget(out instance))
         instance.Callback(null);
   }

   void Callback(object state)
   {
      Console.Write('.');  // do something useful
   }

   public void Dispose()
   {
      Dispose(true);
      GC.SuppressFinalize(this);
   }

   protected virtual void Dispose(bool disposing)
   {
      if (disposing)
      {
         Console.WriteLine("dispose");
         timer.Dispose();
      }
   }

   ~SomethingWithTimer()
   {
      Console.WriteLine("destructor");
      Dispose(false);
   }
}
</code>```

If disposed, the timer will be disposed.

If not disposed, the object will become eligible for garbage collection.

答:
Consider a class that implements IDisposable, but when it is not disposed by its user, it will not become eligible for garbage collection, thus its destructor won’t run, and resources will be leaked.

Your presumption is incorrect. All classes are disposed and a properly written implementation of IDisposable will not leak resources.

To be absolutely clear,

The garbage collector eventually collects all GC memory and does not free non-GC memory. Cyclical references are still collected, when available.

IDisposable exists in order to free non-GC memory (and other resources) and has no role in freeing GC memory.

If Dispose is never called then all the GC memory will still be freed eventually. A properly written implementation of IDisposable will ensure that unmanaged resources will be freed too, even if Dispose is not called.

See http://msdn.microsoft.com/en-us/library/system.idisposable.aspx for details. The relevant quote is:

Because the IDisposable.Dispose implementation is called by the consumer of a type when the resources owned by an instance are no longer needed, you should either wrap the managed object in a SafeHandle (the recommended alternative), or you should override Object.Finalize to free unmanaged resources in the event that the consumer forgets to call Dispose.

If you have a reason to believe this is not so, please provide a reference and explanation why.

Two further points. There is no particular reason to expect that cyclical references cannot be garbage collected. Cycles cause a lot of problems for reference counting, but the GC has no such problems. The algorithm has 3 phases (mark, relocate, compact) and it finds live objects by tracing from 3 places (stack roots, GC handles and static data). Cycles that have no root are simply disposed.

There is a problem lurking here that wasn't mentioned. Although the GC guarantees the eventual finalisation of all objects, during which non-GC resources will be released, it does not guarantee the order in which this will happen. If there are order dependencies among the non-GC resources then relying on finalisation may result in leaks. The solution to that involves the proper allocation and management of non-GC resources, which is outside the scope of this question.


问:
Does it make sense to choose UTF-32, based on concern that some basic rule will be broken for UTF-8?
I'm working on an cross platform C++ project, which doesn't consider unicode, and need change to support unicode.

There is following two choices, and I need to decide which one to choose.

Using UTF-8 (std::string) which will make it easy to support posix system.

Using UTF-32 (std::wstring) which will make it easy to call windows API.

So for item #1 UTF8, the benefit is code change will not too many. But the concern is some basic rule will broken for UTF8, for example,

string.size() will not equal the character length.

search an '/' in path will be hard to implement (I'm not 100% sure).

So any more experience? And which one I should choose?

答:
Use UTF-8. string.size() won't equal the amount of code points, but that is mostly a useless metric anyway. In almost all cases, you should either worry about the number of user-perceived characters/glyphs (and for that, UTF-32 fails just as badly), or about the number of bytes of storage used (for this, UTF-32 is offers no advantage and uses more bytes to boot).

Searching for an ASCII character, such as /, will actually be easier than with other encodings, because you can simply use any byte/ASCII based search routine (even old C strstr if you have 0 terminators). UTF-8 is designed such that all ASCII characters use the same byte representation in UTF-8, and no non-ASCII character shares any byte with any ASCII character.

The Windows API uses UTF-16, and UTF-16 doesn't offer string.size() == code_point_count either. It also shares all downsides of UTF-32, more or less. Furthermore, making the application handle Unicode probably won't be as simple as making all strings UTF-{8,16,32}; good Unicode support can require some tricky logic like normalizing text, handling silly code points well (this can become a security issue for some applications), making string manipulations such as slicing and iteration work with glyphs or code points instead of bytes, etc.

There are more reasons to use UTF-8 (and reasons not to use UTF-{16,32}) than I can reasonably describe here. Please refer to the UTF-8 manifesto if you need more convincing.


问:
How do I go about writing a programming language specification?
I really enjoy programming language design. Sometimes I think my language projects and their potential users would benefit from a comprehensive standards document. I've looked at many language standards, ranging from the very formal (C++) to the rather informal (ECMAScript), but I can't really get a handle on how I should break things down and organise such a document, even though I think I'm pretty good at technical writing in general.

Should I write it like a long tutorial, or more like a formal math paper? How do I keep it up to date if I'm developing it alongside a reference implementation? Should I just give up and treat the implementation and documentation as the de facto standard? Further, is there really any significant benefit to having a standard? Does requiring a standard mean that the language is needlessly complex?

答:
I found the Java language spec both formal and readable, and I think it has a sensible structure.
Some of the W3C specs could be good examples as well.

Doing the formal work could help you keep language complexity down and see the corner cases.

Headings brain dump: source encoding, lexing, fundamental types, literals, operators, expressions, simple statements, conditionals, loops, functions (definitions and calls), type declarations, modules, compilation units, variable scoping, various kinds of name resolution (eg imports, methods), memory model, side effects, typing, concurrency…

ContentLicense: CC BY-SA 2.5


问:
Testing abstract class' behavior
I'm currently refactoring an existing design, which was created without TDD. There is a class hierarchy with one abstract base class and two subclasses. In the original design, these classes were mostly just data holders without much behavior. I have identified some functionality which should be implemented in the base class, and I'd like to write tests for this functionality now. But since the class is abstract, I cannot instantiate it (obviously).

Note: The functionality I'd like to test doesn't invoke any pure virtual methods.

```<code>class Base {}; // Is abstract

TEST(BaseTest, doesSomethingAmazing) {
    Base aBase; // <-------- Not possible!!!
    ASSERT_THAT(aBase.amazeMe(), Eq(AMAZING_RESULT));
}
</code>```

Edit: To clarify a few things:

Inheritance does actually make sense in this situation - both subclasses map to specific domain concepts, and polymorphism helps keep the surrounding code clean

There is behavior which will be used in both subclasses, and which needs data that is common to both classes. So I think it makes sense to put it in a common super class.

I can think of several possible solutions, but none of them seems optimal to me:

Add a subclass to the test code, which implements all pure virtual functions. Downside: Hard to name that subclass in a concise way, understanding the tests becomes harder

Instantiate an object of the subclass instead. Downside: Makes the tests pretty confusing

Add empty implementations to the base class. Downside: Class is not abstract anymore

I tend towards option 3, to make the tests as clear as possible, but I'm not really satisfied with that. Is there a better way I'm not aware of?

答:
As long as the functionality you'd like to test doesn't invoke any pure virtual methods and isn't overridden in subclasses, I'd stick with your bullet point number 1 - creating a test-specific subclass. You could name it Sub<ClassName> or any generic name reflecting that the subclass itself is not important.

Now if what you want to test can be altered in any way by the final concrete class, you might want to consider this :

I don't know if there's an equivalent in the C++ test framework you're using, but NUnit (and I believe JUnit) let you implement the Abstract Test pattern.

In short, you have

An abstract base test class. It contains a abstract factory method used to generate the object under test, and the test methods per se. These methods verify things that must stay true regardless of the concrete object underneath.

As many derived test classes as there are derivatives of the abstract class under test. You just have to implement the factory method here to return an instance of the derived class.

When the test runner sees a derived test class, it will automatically execute all test methods inherited from the base test class against the factory method-generated object.

Title: Testing abstract class' behavior


答:
Under normal circumstances, cyclical references are not a problem for the GC, because it can detect them. But here, the whole object graph looks like this (based on looking at the reference source):

So, the problem isn't just the cycle, it's that you have a static field that references the cycle.

What you could do to fix this is to break the cycle between TimerCallback and Cyclical. In your sample code, that's simple: just changeCallback into a static method. In your real code, breaking the cycle might require more work, like creating a separate class for Callback, or maybe even using WeakReference.

What happens when you do this is that when Cyclical gets GCed, the finalizer of TimerHolder will run, which will stop the timer.

But you should still be careful with this, because the usual caveats for finalizers apply: you never know when will a finalizer run. Especially when you're not allocating much memory, it may take a very long time before it's run.

Title: How to design an IDisposable that unconditionally needs to be disposed?

Body:
Consider a class that implements IDisposable, and that has members in such a way that it will never become eligible for garbage collection when it is not disposed. And as it will not be garbage collected, it will not have the chance to use the destructor for cleaning up.

As a result, when it is not disposed (e.g. unreliable users, programming errors), resources will be leaked.

Is there a general approach how such a class can be designed to deal with such a situation or to avoid it?

Example:

```<code>using System;

class Program
{
    static void Main(string[] args)
    {
        new Cyclical();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.ReadKey();
    }
}

class Cyclical
{
    public Cyclical()
    {
        timer = new System.Threading.Timer(Callback, null, 0, 1000);
    }

    System.Threading.Timer timer;

    void Callback(object state)
    {
        Console.Write('.');  // do something useful
    }

    ~Cyclical()
    {
        Console.WriteLine("destructor");
    }
}
</code>```

(Omitted IDisposable to keep example short.) This class uses a Timer to do something useful at certain intervals. It needs a reference to the Timer to avoid it is garbage collected.

Let’s assume the user of that class will not dispose it. As a result of the timer, somewhere some worker thread has a reference to the Cyclical instance via the callback, and as a result, the Cyclical instance will never become eligible for garbage collection, and its destructor will never run, and resources will leak.

In this example, a possible fix (or workaround) could be to use a helper class that receives callbacks from the Timer, and that does not have a reference, but only a WeakReference to the Cyclical instance, which it calls using that WeakReference.

However, in general, is there a design rule for classes like this that need to be disposed to avoid leaking resources?

For the sake of completeness, here the example including IDispose and including a workaround/solution (and with a hopefully less distracting name):

```<code>class SomethingWithTimer : IDisposable
{
   public SomethingWithTimer()
   {
      timer = new System.Threading.Timer(StaticCallback,
         new WeakReference<SomethingWithTimer>(this), 0, 1000);
   }

   System.Threading.Timer timer;

   static void StaticCallback(object state)
   {
      WeakReference<SomethingWithTimer> instanceRef
         = (WeakReference<SomethingWithTimer>) state;
      SomethingWithTimer instance;
      if (instanceRef.TryGetTarget(out instance))
         instance.Callback(null);
   }

   void Callback(object state)
   {
      Console.Write('.');  // do something useful
   }

   public void Dispose()
   {
      Dispose(true);
      GC.SuppressFinalize(this);
   }

   protected virtual void Dispose(bool disposing)
   {
      if (disposing)
      {
         Console.WriteLine("dispose");
         timer.Dispose();
      }
   }

   ~SomethingWithTimer()
   {
      Console.WriteLine("destructor");
      Dispose(false);
   }
}
</code>```

If disposed, the timer will be disposed.

If not disposed, the object will become eligible for garbage collection.


问:
Flexible authorization design in ASP.NET pages?
I'm developing an ASP.NET webforms application with pages which displays information based on the authorization level of the authenticated user (very typical). I will write a simple example of the issue I'm facing:

Let's pose I want to have a page with 4 buttons:

1- "OnlyForAdmins" button.
2- "OnlyForManagersAndAdmins" button
3- "Guest" button
4- "Authenticated" button

Depending on the permission level of the visitor, one or several buttons must be displayed. Right now in code behind buttons are handled in the following way:

```<code>public void Page_Load(object sender, EventArgs e)
{
    if (HttpContext.Current.User.Identity.IsAuthenticated)
        Athenticated.Visible = true;
    if (HttpContext.Current.User.IsInRole("Admins"))
        OnlyForAdmins.Visible = true;
    if (HttpContext.Current.User.IsInRole("Manager") || HttpContext.Current.User.IsInRole("Admins"))
        OnlyForManagersAndAdmin.Visible = true;
}
</code>```

While this works, honestly I think that this approach is rather inflexible, having to add more "ifs" for every new role I introduce.

I wonder if there exist approaches to handle this kind of problems. I'd be grateful if someone can enlighten me.

Thank you.

答:
I'd do it this way:

A user can hold a number of Roles within your application (including none).  These will be retrieved from an external data store.

Any control within your application is available to any number of Roles.  These might be statically defined or loaded from an external data store.

A Control becomes "available" when the current User's Role set intersects with the Roles required to access that Control.

For example:

Button1 might be "tagged" with the "Admin" and "Manager" roles.

Button2 might be tagged with just the "Admin" role.

Manager3 might have the "Authenticated" and "Manager" roles.  They can access Button1.

Admin4 will have the "Authenticated" and "Admin" roles.  They can access both buttons.

Guest5 has no Roles at all (being unauthenticated) and can use neither button.


问:
Running multiple versions on the same .NET website
I have a website (which is actually mainly a Web API site) and I'd like to be able to simultaneously access multiple versions of it.

What I'm currently doing is creating a new website for each version under IIS and referring to sync2.site.com, sync3.site.com etc.

This solution is not very scale able nor maintainable.

How to quickly add more "versions" of this app and access them using something like sync.site.com?version=3?

答:
At my job we do this currently fairly easily just by putting each version under it's own application folder in IIS, so we have URIs like:

```<code>http://SomeServiceBox/Service/v1.0/
http://SomeServiceBox/Service/v1.1/
http://SomeServiceBox/Service/v2.0/
http://SomeServiceBox/Service/v2.3/
</code>```

Works just fine for us. I can only suggest this until you explain why you wouldn't already be doing such... I'm guessing there's something in the way your service is put together that makes such an approach non-functioning otherwise you would have already done this.

Body:
At my job we do this currently fairly easily just by putting each version under it's own application folder in IIS, so we have URIs like:

http://SomeServiceBox/Service/v1.0/
http://SomeServiceBox/Service/v1.1/
http://SomeServiceBox/Service/v2.0/
http://SomeServiceBox/Service/v2.3/

Works just fine for us. I can only suggest this until you explain why you wouldn't already be doing such... I'm guessing there's something in the way your service is put together that makes such an approach non-functioning otherwise you would have already done this.


问:
Worried about memory leak in DLL that creates a dynamic sized array
I have a  wrapper DLL that interfaces to another DLL that contains the following function:

```<code>char * Foobar(void)
{

    // BLAH is the function from the DLL this wrapper interfaces too
    char *array = 0; // Set up an array pointer for dynamic memory allocation.
    int NumOfChar = 0;

    // Build array
    for (int n=0; (*(BLAH+n) != '\0'); n++)
    {
            NumOfChar++; // keep track of how big BLAH is.
    }

    NumOfChar++;    // +1 so I can re-add the NULL

    // Try to allocate an array based on the size of BLAH This is dynamic...
    if (!(array = new char[NumOfChar]))
    {
        // If there's a problem allocating the memory, pop up a message.
        MessageBox (0, "Error: out of memory.", "Crap", MB_OK);
    }
    else
    {
        memcpy(array, BLAH,(NumOfChar)); // copy the contents of BLAH to array.
    }

    array[NumOfChar+1]='\0'; // ensure the last character is a NULL

    FreeLibrary(hGetProcIDDLL); // release the DLL

    return array;
}
</code>```

I am calling this DLL from LabVIEW which is don't think is specific to this question, as the DLL can be called by any program. My question is once Foobar returns the pointer to the array, how can I make sure that the array is deallocated afterwards? This seems to be a memory leak, because next time this routine is called, the next array won't necessarily overwrite the old array. It will just use up more and more memory, am I correct in this logic?

Thank you

答:
Yes, you're allocating memory but not freeing it, so there is a memory leak.

A good approach is to allocate and deallocate the memory in the same place, i.e. wherever the DLL is called from - in your case, LabVIEW. That is, make your function void Foobar(char *array) (or int Foobar(char *array) and return the array length). Then you just need to make sure you call the function with big enough array. Perhaps add another parameter do indicate the maximum allowed length, int Foobar(char *array, int maxLen) to react instead of crashing in case of insufficient length.


问:
What is the difference between programming for microcontrollers and programming for embedded systems?
What is the difference precisely between an Embedded System (like Tegra, Raspberry or similar) and a Microcontroller? I understand there is a difference but I'm finding it difficult to understand.

What does one intent when he says: "are you able to develop for microcontrollers"? Does it mean simply program in C/C++ for an embedded system or something more? What is the difference between programming in C/C++ for Embedded Systems and Microcontrollers? If I commonly program for ARM in C/C++, can I say that I can program microcontrollers or can I apply for such a job?

答:
This is all my experience/opinion, gathered from working in the field pretty close to the metal:

"embedded systems" are usually situations where you have significant non-trivial memory or speed constraints as compared to desktop systems. Those embedded situations can include microcontrollers, but can also include x86 systems on a chip, and also systems like PC104 or other form factors. They can run a "common" OS like Linux or Windows CE, but not always. They usually have a lot less memory and speed than desktop/server applications, but usually not so little that you have to think long and hard about whether to use a 16 or 32 bit integer for something like you might have to with a microcontroller.

The raspberry pi for example runs at 700MHz and has 256 or 512 megabytes of ram. An Atmel ATMega32U4 microcontroller for example runs at up to only 16MHz, with only 2560 bytes of ram. Some of the STM32 devices, which utilize an ARM cores, run at up to 24MHz and have about 8 kB or so of ram. Quite a substantial difference in speed and memory between the two, even more dramatic than a desktop vs a raspberry pi.

Programming for microcontrollers is a subset of embedded systems with even more significant memory and speed constraints, but also closer intimacy with the hardware the microcontroller is wired to. You'll spend a lot more time thinking about falling or rising edge clock triggers, watchdog timers, external interrupt triggers, analog to digital conversion timing issues and a bunch of other stuff that is typically long abstracted away in desktop systems. You may even have to be mindful of how much power is being used in different operations, and have to write your software to meet power draw requirements.

Until you have programmed for microcontrollers, it is unwise to claim you can. Until the day comes that you have to use an oscilloscope to figure out why your SPI-bus peripherals aren't talking, you don't yet know the kinds of things that have so far been invisible to you.

ContentLicense: CC BY-SA 4.0


问:
alternate approach of binary serialization/de-serialization
Is it possible to convert a list of object directly to byte[] (and vice versa) to gain performance (by avoiding serialization/de-serialization)?

What I have in mind is that a list is somewhere in memory(heap). If I could read the bytes in heap for my list I could just assign it a variable (of byte[]) in my program. Is it possible? and if yes, how would I get back the original list from byte[] without de-serializing using BinaryFormatter?

答:
The .NET heap is an object graph, only blittable types will have a contiguous memory block for you to scrape. If you pinned an object and everything it referenced, and everything that stuff referenced recursively pinning the entire object graph you wanted to serialize, then you could start walking the object graph scraping it all into a contiguous byte array logically. Without pinning, the GC would move those objects around so you wouldn't be able to follow their memory links to know where to scrape data from the memory.

But this really wouldn't help you any because you'd be scraping objects that have pointers to memory addresses, and to reconstruct the object graph you'd have to reuse those exact memory addresses for all the pointers to line up - you have no way of knowing if those memory addresses would be available at another time. Alternatively you'd have to dig into the memory space of those objects; identify the pointer members and alter the addresses they pointed at to point them to where you construct their related nodes. This would be an absolute metric ton of work just to avoid serialization which is considerably less work and less dangerous.


答: Wirth designed and implemented many programming languages: of these, the specifications for the Oberon and Oberon2 languages are notable for there completeness, terseness and readability.</p>

Title: How do I go about writing a programming language specification?

Body:
I really enjoy programming language design. Sometimes I think my language projects and their potential users would benefit from a comprehensive standards document. I've looked at many language standards, ranging from the very formal (C++) to the rather informal (ECMAScript), but I can't really get a handle on how I should break things down and organise such a document, even though I think I'm pretty good at technical writing in general.

Should I write it like a long tutorial, or more like a formal math paper? How do I keep it up to date if I'm developing it alongside a reference implementation? Should I just give up and treat the implementation and documentation as the de facto standard? Further, is there really any significant benefit to having a standard? Does requiring a standard mean that the language is needlessly complex?


问:
Use one or multiple files for graphics properties?
I'm creating a 2D game in plain ANSI-C using SDL2. I'm planning to let users create their own graphics. So, to achieve this, I'll use an information file which will hold some data such as Width, Height, X and Y position of each frame. But I have two views of this. One is to use a single file which will hold the information of all graphics. The other is to use one file for each graphic. Which one is faster and cleaner? Or it's just the same?</p>

答:
Using one file is cleaner, but also, files have to take up a minimum space (On my disk, 16kb, this is called the cluster size). So if you're creating lots of small files, even if each one is only one byte long, if you have 1000 files, that's nearly 16 megabytes!

It depends on the size of the files stored with each graphic, to summarize:

Multi-File advantages:

A corrupted file will not effect all graphics.

You don't need to search for the part of the file you want.

Clearer code

Single file advantages:

You don't have issues with cluster size

Potentially faster accessing as you don't need to open multiple files

It also depends if this information will be streamed, or read once at startup. If it's read once at startup, then speed of accessing doesn't matter so much.
Personally, if you're going to end up with lots of really small files, I'd go with one larger file, but if you're going to end up with less files of more reasonable sizes, I'd go for a file per graphic


答: The key here is that you want end users to be able to add graphics.  If thats the case, I'd recommend individual files for the graphics, this way customers don't have to edit existing files (and possibly corrupt them), and its easier to distribute art for the game by just copying files into their directory - no need to edit existing files.</p>

Title: Use one or multiple files for graphics properties?

Body: I'm creating a 2D game in plain ANSI-C using SDL2. I'm planning to let users create their own graphics. So, to achieve this, I'll use an information file which will hold some data such as Width, Height, X and Y position of each frame. But I have two views of this. One is to use a single file which will hold the information of all graphics. The other is to use one file for each graphic. Which one is faster and cleaner? Or it's just the same?</p>


问:
What to test in this project?
Every developer advocates test-driven development, but I am coding a website in NodeJS and I am not testing my app.

This is not because I don't see any reason. I know it allow me to check at each commit whether my code is right, thus avoiding security flaws.

I don't do any tests because I don't know how or what to test. I coded a MVC app with express + mongoose + passport, and I have no idea what to test or how to test. I know it is possible to mock express requests or mongodb, but I don' find that clean and flexible.

So, what and how to test?

答:
If you want to test your code independently of NodeJS, create a service layer or repository layer that contains an API you can call on one side, and Node.JS calls on the other.  You can use your stubs or mocks on the methods in that layer, or even swap out the entire implementation of the service layer if that works for you.

What you test is the same as it ever was: methods.

Title: What to test in this project?


问:
What encoding is used by javax.xml.transform.Transformer?
Please can you answer a couple of questions based on the code below (excludes the try/catch blocks), which transforms input XML and XSL files into an output XSL-FO file:

```<code>File xslFile = new File("inXslFile.xsl");
File xmlFile = new File("sourceXmlFile.xml");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(xslFile));
FileOutputStream fos = new FileOutputStream(new File("outFoFile.fo");
transformer.transform(new StreamSource(xmlFile), new StreamResult(fos));
</code>```

inXslFile is encoded using UTF-8 - however there are no tags in file which states this.
sourceXmlFile is UTF-8 encoded and there may be a metatag at start of file indicating this.

am currently using Java 6 with intention of upgrading in the future.

What encoding is used when reading the xslFile?

What encoding is used when reading the xmlFile?

What  encoding will be applied to the FO outfile?

How can I obtain the info (properties) for 1 - 3? Is there a method call?

How can the properties in 4 be altered - using configuration and dynamically?

if known - Where is there info (web site) on this that I can read - I have looked without much success.

答:
What encoding is used when reading the xslFile?

What encoding is used when reading the xmlFile?

How can I obtain the info (properties) for 1 - 3? Is there a method call?

There is no clear way to retrieve this information from the Transformer API.  Source encoding is only relevant to a parser, and then only while parsing a particular document or fragment from a stream of bytes.

I imagine you ask this because you've run into issues with encoding and are looking for a way to debug it.  A common issue is that XML documents are marked as being in encoding ABC, but are actually encoded through XYZ, so... verify that your XML documents are stored in the encoding they claim.

If you're forced to a guess, it's probably encoded in Windows-1252 / Cp1252 and the XML document will either claim to be UTF-8 or won't have a declaration.

There are two ways around this:

convert the file with iconv or a text editor like Notepad++, or

add encoding="windows-1252" to the <?xml instruction.

If you're going to deploy to non-Windows machines, keep in mind that a JVM is not required to support windows-1252 / cp1252 (though they support its close relativeISO-8859-1):

Standard charsets

Every implementation of the Java platform is required to support the following standard charsets. Consult the release documentation for your implementation to see if any other charsets are supported. The behavior of such optional charsets may differ between implementations.

US-ASCII    Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set

ISO-8859-1      ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1

UTF-8   Eight-bit UCS Transformation Format

UTF-16BE    Sixteen-bit UCS Transformation Format, big-endian byte order

UTF-16LE    Sixteen-bit UCS Transformation Format, little-endian byte order

UTF-16  Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark


问:
Do resumable exceptions make any sense?
Following up my previous question I wonder if resumable exceptions make any sense. It looks like nobody uses them in Java. Don't they use resumable exceptions because of Java limitations or just because they don't really need them?

Suppose, I want to create a file in a directory, which should exist but does not. I would probably prefer use a resumable exception (i.e. throw an exception, catch it and create the directory, and resume the execution) instead of testing if the directory exists every time I create a file.  Does it make sense in general ?

答:
A Smalltalk web framework 'Seaside' uses resumable expections.

The gain: You can write code which follows a users walk through the web-pages (asks and resumes).

The alternative (with common web-frameworks and languages which do not support resumable exceptions) is to split your code into small, unrelated chunks and session-state.

OwnerDisplayName: Misha

Title: Do resumable exceptions make any sense?


问:
equivalence in callback and non-callback javascript
I'm pretty sure that the following two snippets are equivalent but I wanted to double check:

CALLBACK STYLE

```<code>function foo(input, callback) {
    // do stuff with input

    callback();
}

function bar(input, callback) {
    // do stuff with input

    callback();
}

foo("hi", bar("bye", function() {
                       // do something cool
                     }));
</code>```

Note that the callbacks take no arguments.

PLAIN STYLE

```<code>function foo(input) {
    // do stuff with input
}

function bar(input) {
    // do stuff with input
}

foo("hi");
bar("bye");
(function() {
    // do something cool
})();
</code>```

Of course if they are equivalent it would make sense to me to use PLAIN STYLE as it's simpler and cleaner.

I realize the scope of the anonymous function (who does something cool) is different in the two cases.. I'm not concerned with that aspect of "equivalence".

UPDATE

I'm working on some legacy code and find quite a bit of it confusing. This is the original code that prompted this question. Specifically the noted 6 or so lines of code.

```<code>var CoolNamespace = (function () {
    var container_element,
        keysLength = 0;

    //
    // THE FOLLOWING 6 OR SO LINES IS WHAT I'M CURIOUS ABOUT
    //
    _createCoolObject(function (coolObject) {
        _appendFrameToContainer(coolObject, function () {

            // Post form
            _sendForm(function (form) {
                container_element.appendChild(form);
                form.submit();
            });
        });
    });

    function _sendForm (callback) {
        // Sends client data via post.
        if (keysLength != 0) {
            var form = _createForm();
        } else {
            throw new Error("error message stub");
        }
        callback(form);
    }

    function _appendFrameToContainer (frame, callback) {
        if (typeof container_element != "undefined") {
            container_element.appendChild(frame);
        } else {
            throw new Error("error message stub");
        }
        callback();
    }

    function _createCoolObject (callback) {
        var coolObject = { level: "very cool" };

        callback(coolObject);
    }

    function _handleMessage (event) {
        // it's not really about this function
    }

    function _createForm() {
        // it's not really about this function either
        var form;
        return form;
    }
})();
</code>```

When stepping through the code, it seemed to be the case that the body of _createCoolObject was invoked before the argument (which is a function). I think my confusion was that a the argument to _createCoolObject is a function literal which evaluates to a function but that function is not itself evaluated until the line callback(coolObject). Thanks for the clarification!!

答:
They are not equivalent in their execution order.

```<code>foo("hi", bar("bye", function() {
    // do something cool
}));
</code>```

This must first evaluate bar("bye", function() { … }), then calls foo("hi", …) with the result of that invocation. As the return value of bar is undefined, you'll get an error when you call that as a function.

If you want the callback example to be equivalent to your plain example, you'd have to do:

```<code>foo("hi", function() {
    return bar("bye", function () {
        // do something cool
    });
});
</code>```

I would also change the definition of foo and bar so that they do return callback(), which allows for more general code.

Notice that this callback style is similar – but not equivalent – to continuation passing style.

Body:
They are not equivalent in their execution order.

foo("hi", bar("bye", function() {
    // do something cool
}));

This must first evaluate bar("bye", function() { … }), then calls foo("hi", …) with the result of that invocation. As the return value of bar is undefined, you'll get an error when you call that as a function.

If you want the callback example to be equivalent to your plain example, you'd have to do:

foo("hi", function() {
    return bar("bye", function () {
        // do something cool
    });
});

I would also change the definition of foo and bar so that they do return callback(), which allows for more general code.

Notice that this callback style is similar – but not equivalent – to continuation passing style.


问:
What is the pattern for a safe interface in C++
Note: the following is C++03 code, but we expect a move to C++11 in the next two years, so we must keep that in mind.

I'm writing a guideline (for newbies, among others) about how to write an abstract interface in C++. I've read both articles of Sutter on the subject, searched the internet for examples and answers, and made some tests.

This code must NOT compile!

```<code>void foo(SomeInterface & a, SomeInterface & b)
{
   SomeInterface c ;               // must not be default-constructible
   SomeInterface d(a);             // must not be copy-constructible
   a = b ;                         // must not be assignable
}
</code>```

All the behaviors above find the source of their problem in slicing: The abstract interface (or non-leaf class in the hierarchy) should not be constructible nor copiable/assignable, EVEN if the derived class can be.

0th Solution: the basic interface

```<code>class VirtuallyDestructible
{
   public :
      virtual ~VirtuallyDestructible() {}
} ;
</code>```

This solution is plain, and somewhat naive: It fails all our constraints: It can be default-constructed, copy-constructed and copy-assigned (I'm not even sure about move constructors and assignment, but I have still 2 years to figure it out).

We can't declare the destructor pure virtual because we need to keep it inline, and some of our compilers won't digest pure virtual methods with inline empty body.

Yes, the only point of this class is to make the implementers virtually destructible, which is a rare case.

Even if we had an additional virtual pure method (which is the majority of the cases), this class would be still copy-assignable.

So, no...

1st Solution: boost::noncopyable

```<code>class VirtuallyDestructible : boost::noncopyable
{
   public :
      virtual ~VirtuallyDestructible() {}
} ;
</code>```

This solution is the best, because it is plain, clear, and C++ (no macros)

The problem is that it still doesn't work for that specific interface because VirtuallyConstructible can still be default-constructed.

We can't declare the destructor pure virtual because we need to keep it inline, and some of our compilers won't digest it.

Yes, the only point of this class is to make the implementers virtually destructible, which is a rare case.

Another problem is that classes implementing the non-copyable interface must then explicitly declare/define the copy constructor and the assignment operator if they need to have those methods (and in our code, we have value classes that can still be accessed by our client through interfaces).

This goes against the Rule of Zero, which is where we want to go: If the default implementation is ok, then we should be able to use it.

2nd Solution: make them protected!

```<code>class MyInterface
{
   public :
      virtual ~MyInterface() {}

   protected :
      // With C++11, these methods would be "= default"
      MyInterface() {}
      MyInterface(const MyInterface & ) {}
      MyInterface & operator = (const MyInterface & ) { return *this ; }
      MyInterface(MyInterface && ) noexcept {}
      MyInterface & operator = (MyInterface && ) noexcept { return *this ; }
} ;
</code>```

This pattern follows the technical constraints we had (at least in user code): MyInterface cannot be default-constructed, cannot be copy-constructed and cannot be copy-assigned.

Also, it imposes no artificial constraints to implementing classes, which are then free to follow the Rule of Zero, or even declare a few constructors/operators as "= default" in C++11/14 without problem.

Now, this is quite verbose, and an alternative would be using a macro, something like:

```<code>class MyInterface
{
   public :
      virtual ~MyInterface() {}

   protected :
      DECLARE_AS_NON_SLICEABLE(MyInterface) ;
} ;
</code>```

The protected must remain outside the macro (because it has no scope).

Correctly "namespaced" (that is, prefixed with the name of your company or product), the macro should be harmless.

And the advantage is that the code is factored in one source, instead of being copy pasted in all interfaces. Should the move-constructor and move-assignment be explicitly disabled the same way in the future, this would be a very light change in the code.

Conclusion

Am I paranoid to want the code to be protected against slicing in interfaces? (I believe I'm not, but one never knows...)

What is the best solution among the ones above?

Is there another, better solution?

Please remember that this is a pattern that will serve as a guideline for newbies (among others), so a solution like: "Each case should have its implementation" is not a viable solution.

Bounty and results

I awarded the bounty to coredump because of the time spent to answer the questions, and the relevance of the answers.

My solution to the problem will probably go to something like that:

```<code>class MyInterface
{
   DECLARE_CLASS_AS_INTERFACE(MyInterface) ;

   public :
      // the virtual methods
} ;
</code>```

... with the following macro:

```<code>#define DECLARE_CLASS_AS_INTERFACE(ClassName)                                \
   public :                                                                  \
      virtual ~ClassName() {}                                                \
   protected :                                                               \
      ClassName() {}                                                         \
      ClassName(const ClassName & ) {}                                       \
      ClassName & operator = (const ClassName & ) { return *this ; }         \
      ClassName(ClassName && ) noexcept {}                                   \
      ClassName & operator = (ClassName && ) noexcept { return *this ; }     \
   private :
</code>```

This is a viable solution for my problem for the following reasons:

This class cannot be instantiated (the constructors are protected)

This class can be virtually destroyed

This class can be inherited without imposing undue constraints on inheriting classes (e.g. the inheriting class could be by default copiable/moveable)

The use of the macro means the interface "declaration" is easily recognizable (and searchable), and its code is factored in one place making it easier to modify (a suitably prefixed name will remove undesirable name clashes)

Note that the other answers gave valuable insight. Thank you to all you who gave it a shot.

Note that I guess I can still put another bounty on this question, and I value enlightning answers enough that should I see one, I would open a bounty just to assign it to that answer.

答:
You're not paranoid. My first professional task as a C++ programmer resulted in slicing and crashing. I know of others. There are not a lot of good solutions for this.

Given your compiler constraints, option 2 is the best. Instead of making a macro, which your new programmers will view as weird and mysterious, I would suggest a script or tool for auto generating the code. If your new employees will be using an IDE, you should be able to create a "New MYCOMPANY Interface" tool that will ask for the interface name, and create the structure you are looking for.

If your programmers are using command line, then use whatever scripting language is available to you to create the NewMyCompanyInterface script to generate the code.

I have used this approach in the past for common code patterns (interfaces, state machines, etc). The nice part is that new programmers can read the output and understand it easily, reproducing the needed code when they need something that can't be generated.

Macros and other meta-programming approaches tend to obfuscate what is happening, and the new programmers don't learn what is happening 'behind the curtain'. When they have to break the pattern, they are just as lost as before.

OwnerDisplayName: paercebal


问:
Guessing a phone number's country code
This is the problem I'm working with: given a phone number from anywhere in the world and some location information (state, province, possibly country name if I'm lucky, etc.), return the ISO country code for that number.

For the purposes of this question, I will not focus on the location information, as that provides an alternative solution to determining the country code which doesn't even need to use the phone number anymore (though, it would be useful for validation purposes)

When I first started working on the problem, I was hoping there was a deterministic way to figure this out because there was some sort of international standard out there. It became immediately apparent that one does not exist for phone numbers. There are standards within countries, between countries (NANP for example), but no unified international standard.

Playing around with libphonenumbers for a few days, it seems to be able to provide accurate validation of a phone number if I'm given a country code (eg: CA for Canada, GB for United Kingdom, etc).

The library provides two methods: isPossibleNumber, and isValidNumberForRegion. This is the code I'm using

```<code>boolean isValid;
PhoneNumber number;
PhoneNumberUtil util = PhoneNumberUtil.getInstance();

String numStr = "(123) 456-7890";
for (String r : util.getSupportedRegions())
{
    try {
        // check if it's a possible number
        isValid = util.isPossibleNumber(numStr, r);
        if (isValid)
        {
            number = util.parse(numStr, r);

            // check if it's a valid number for the given region
            isValid = util.isValidNumberForRegion(number, r);
            if (isValid)
                System.out.println(r + ": " + number.getCountryCode() + ", " + number.getNationalNumber());
        }
    } catch (NumberParseException e)
    {
        e.printStackTrace();
    }
}
</code>```

So for example, if I took an arbitrary phone number like +44 20 7930 4832 and ran it through the method, I would get the following output

```<code>GB: 44, 2079304832
</code>```

Now, that's assuming I'm given the dialing code (sometimes it's there). If I weren't given the dialing code, I might just get something like 20 7930 4832, and the results are not as pretty

```<code>DE: 49, 2079304832
US: 1, 2079304832
GB: 44, 2079304832
FI: 358, 2079304832
AX: 358, 2079304832
RS: 381, 2079304832
CN: 86, 2079304832
NZ: 64, 2079304832
IN: 91, 2079304832
IR: 98, 2079304832
JP: 81, 2079304832
</code>```

Given a phone number, I can run it through all of the different rules for every country and filter the list down from 244 to around 20 or less if I'm lucky, but I'm not sure if there's anything else I could do to try and guess the country.

答:
[T]hese numbers aren't clients we're working with. They are the calls that our clients have made, which can be anyone, anywhere in the world. Depending on how the service provider chooses to format their data, we may or may not have all of the information we need.

Always ready to help the wire-tapping community! :D

On a more serious note, how much effort would you need to expend?  Are the requirements on accuracy stringent, and do you need to mark how confident you are in the answer?

There are a number of heuristics I imagine could be useful.

Narrow phone numbers down to cities/areas.  If the phone number matches a city with 2 million people and a bunch of towns with 6k people, it's most likely from the country with the big city.  (Perhaps the same can be done with the carriers?)

Do you have a timestamp from the call?  More likely that a call would happen close to business hours.  That may make a few time zones less likely.

Do you have the other phone number in the call?  It may be that the callers are more likely to be in the same or neighbouring countries, or countries that share at least one language.  Maybe not so useful, since you mention that your clients may call anyone across the globe.

Do you have some sort of call history per client?  If you can't narrow down a phone number, but it is possibly in a country that your client frequently communicates with, that's another mark up for that probability.

Maybe these extra guesses can narrow it down to three or five likely suspects.  It remains a guessing game without the international prefix, though.  Specifically, while each criterion may make it more likely to be country ABC, not matching the criteria doesn't make it impossible.

Title: Guessing a phone number's country code


问:
In c++, difference between linking a class object and just including it.
this is my first time here.

I'm a physics grad student and I've recently found a research group to work with. We study statistical mechanics using computer models, so there is a significant programming aspect to it.

My first job has been to take the old data analysis code (written in java) and clean it up in c++. The guy before me who wrote the original program used the traditional physics method of using an enormous amount of spaghetti code and shoving it all in a constructor. This irked me quite a bit, so I divided it up into separate classes and now it has a reasonable class structure.

In the past, whenever we had defined a class we would put its definitions and its methods in a header function, then to use it we would just include it. I know this breaks the rules of how to use .h and .cpp files, but is there any reason other than code etiquette to compile and link a class object rather than include it?

Sorry for the long question.

答:
The idea of headers is that we separate the public interface (i.e. declarations) from internal implementation details (i.e. the actual method bodies). This split has all kinds of advantages:

There's a helper function I need? Let's just put it into the .cpp file, and outside code cannot see it. I can also do things like using std without interfering with other code.

We are stuck in a C mindset and want to use a macro? Declare it in the .cpp file to avoid polluting outside code.

There is a bug in a method? After fixing it, we only need to recompile that single .cpp file and re-link the application. This is much faster than recompiling everything.

Related to that: header files are often included multiple times, and are therefore recompiled again and again … conserver compilation time, and put as little information as possible into the headers.

Headers make the handling of cyclic dependencies across multiple files possible.

There are also a few drawbacks with headers, but you can't do anything to change that: headers are code duplication, they are idiotic language design, the C preprocessor is of an outdated design, and encapsulation (the split between public interface and implementation details) doesn't work in C++ because private fields of a class are part of the public interface.

What do we take from that? Mainly the point about compilation time. Headers allow you to recompile only those parts that have changed. This should be supported by virtually any build chain – learn about the make program if you are currently doing everything by hand.


问:
Using mocks to set up object even if you will not be mocking any behavior or verifying any interaction with it?
When building a unit test, is it appropriate to use a mocking tool to assist you in setting up an object even if you will not be mocking any behavior or verifying any interaction with that object?

Here is a simple example in pseudo-code:

```<code>//an object we actually want to mock
Object someMockedObject = new Mock(Object.class);
EqualityChecker checker = new EqualityChecker(someMockedObject);

//an object we are stubbing/mocking only to avoid figuring out how to instantiate or
//tying ourselves to some constructor that may be removed in the future
ComplicatedObject someObjectThatIsHardToInstantiate = new Mock(ComplicatedObject.class);

//set the expectation on the mock
When(someMockedObject).equals(someObjectThatIsHardToInstantiate).return(false);
Assert(equalityChecker.check(someObjectThatIsHardToInstantiate)).isFalse();

//verify that the mock was interacted with properly
Verify(someMockedObject).equals(someObjectThatIsHardToInstantiate).oneTime();
</code>```

Is it appropriate to mock ComplicatedObject in this scenario?

答:
With Mockito, I would use the any() matcher.

```<code>When(someMockedObject).equals(any(ComplicatedObject.class)).return(false);
</code>```

There might be something similar in your mocking framework.

Body:
With Mockito, I would use the any() matcher.

When(someMockedObject).equals(any(ComplicatedObject.class)).return(false);

There might be something similar in your mocking framework.


问:
Would using a hash table in garbage collection solve the stop the world problem of mark and sweep?
In mark-sweep-compact garbage collection algorithm you have to stop-the-world when relocating objects because reference graph becomes inconsistent and you have to replace values of all references pointing to the object.

But what if you had a hash table with object ID as a key and pointer as value, and references would point to said ID instead of object address... then fixing references would only require changing one value and pause would only be needed if object is tried to be written into during copying...

Is there a mistake in my line of thought?

答:
Updating references is not the only thing that requires a pause. The standard algorithms commonly grouped under "mark-sweep" all assume that the entire object graph remains unaltered while it's being marked. Correctly handling modifications (new objects created, references changed) requires rather tricky alternative algorithms, like as the tri-color algorithm. The umbrella term is "concurrent garbage collection".

But yes, updating references after compaction also needs a pause. And yes, using indirection (e.g. via a persistent object ID and a hash table to real pointers) can greatly reduce the pausing. It might even be possible to make this part lock-free if one so desires. It would still be as tricky to get right as any low-level shared-memory concurrency, but there is no fundamental reason it wouldn't work.

However, it would have severe disadvantages. Aside from taking extra space (at least two extra words for all objects), it makes every dereference much more expensive. Even something as simple as getting an attribute now involves a full hash table search. I'd estimate the performance hit to be way worse than for incremental tracing.


答:
All problems in computer science can be solved by another level of indirection … except for the problem of too many layers of indirection

Your approach does not immediately solve the problem of garbage collection, but only moves it up one level. And at what cost! Now, every memory access goes through another pointer dereference. We can't cache the result location, because it might have been relocated in the meanwhile, we must always go through the object ID. In most systems, this indirection is not acceptable, and stopping the world is assumed to have a lower total runtime cost.

I said your proposition only moves the problem, not solves it. The issue is around the reuse of object IDs. The object IDs are now our equivalent of pointers, and there is only a finite amount of addresses. It is conceivable (esp. on a 32 bit system) that during the lifetime of your program, more than INT_MAX objects will have been created, e.g. in a loop like

```<code>while (true) {
    Object garbage = new Object();
}
</code>```

If we just increment the object ID for each object, we will run out of IDs at some point. Therefore we have to find out which IDs are still in use and which are free so that they can be reclaimed. Sound familiar? We are now back at square one.

Title: Would using a hash table in garbage collection solve the stop the world problem of mark and sweep?

Body:
In mark-sweep-compact garbage collection algorithm you have to stop-the-world when relocating objects because reference graph becomes inconsistent and you have to replace values of all references pointing to the object.

But what if you had a hash table with object ID as a key and pointer as value, and references would point to said ID instead of object address... then fixing references would only require changing one value and pause would only be needed if object is tried to be written into during copying...

Is there a mistake in my line of thought?

Body:
All problems in computer science can be solved by another level of indirection … except for the problem of too many layers of indirection

Your approach does not immediately solve the problem of garbage collection, but only moves it up one level. And at what cost! Now, every memory access goes through another pointer dereference. We can't cache the result location, because it might have been relocated in the meanwhile, we must always go through the object ID. In most systems, this indirection is not acceptable, and stopping the world is assumed to have a lower total runtime cost.

I said your proposition only moves the problem, not solves it. The issue is around the reuse of object IDs. The object IDs are now our equivalent of pointers, and there is only a finite amount of addresses. It is conceivable (esp. on a 32 bit system) that during the lifetime of your program, more than INT_MAX objects will have been created, e.g. in a loop like

while (true) {
    Object garbage = new Object();
}

If we just increment the object ID for each object, we will run out of IDs at some point. Therefore we have to find out which IDs are still in use and which are free so that they can be reclaimed. Sound familiar? We are now back at square one.


问:
How do you learn Regular Expressions?
I'm not asking where to learn. I've found lots of good resources online, and books etc.

But how the heck do I tackle them. Where is the start of it, the end? When does the regexp processor advance on the text, when does it hold its stand and tries another match? etc.

I feel like trying to figure out hieroglyphs on the Egyptian pyramids.

答:
One approach I used was to find a bunch of open source projects that needed syntax updates and then write a increasingly complex sed script, which was comprised of many regular expressions.

The script needed to run against many different files in each open source project.  Then be run against many different projects with different styles.  I started with something very simple like %s/before/after  then I found that it matched too many cases.  so I added more stuff to prevent that.  Then I found different projects using different syntax styles that needed different changes.

In the end I ended up with

great skills and knowledge about regular expressions

good skills with sed

helping out many open source projects

getting a lot of contribution activity shown on my github profile

another good 'swiss-army knife' tool for the virtual toolbelt

and was helped in this approach by the need to

achieve actual goals without cheating

use the (regex) skills as part of a greater goal with greater motivation.

be able to show proof of the skills I learned by changing others code and then having the changes reviewed.

I will also pass along that there are a bunch of sites for the various languages - ruby, javascript, etc. that will let you play around with expressions and sample text for immediate gratification.  These are:

Ruby - http://rubular.com

Python - https://pythex.org

Javascript - http://scriptular.com

Java - http://www.regexplanet.com/advanced/java/index.html

.net - http://regexhero.net/

regexes in multiple languages on one site

http://regex101.com/ javascript / php / python

http://myregextester.com/ PHP / JAVA / JS / ASP / .NET / C# / VB.NET

focus on the match groups:

https://www.debuggex.com/

Title: How do you learn Regular Expressions?


问:
Which one of these answers regarding functions is incorrect?
So while I've been doing some lengthy compiles I decided to take the C++ general test on ODesk  and came across this question.

If I'm not mistaken, given the wording (or lack thereof) all of these could be true.

a.

```<code>int Foo() { }
int Foo(int bar) { }
</code>```

b.
Well, return void; would be incorrect semantically but functions can obviously have void return types.

```<code>void Foo() { }
</code>```

c. This is the definition of inline functions, yes.

d.
Without going into much detail about the placement of the following elements,

```<code>typedef void (*Func)(int);

Func functions[2];

void Foo(int bar) { }
void Bar(int foo) { }

functions[0] = &Foo;
functions[1] = &Bar;
</code>```

Further, you could always do this using lambdas and functors.

e.

```<code>void Foo(int& bar)
{
    ++bar;
}

int foobar = 5;
Foo(foobar);
</code>```

f.

```<code>int bar = 5;

int& GetBar()
{
    return bar;
}

GetBar() = 6;
</code>```

g.

```<code>int bar = 5;

int* GetBar()
{
    return &bar;
}

(*GetBar()) = 5;
</code>```

I fail to see where this question has any truly false answers. Am I missing something?

Needless to say I ran out of time and failed the whole thing. I guess I'm a bad C++ programmer. :(

答:
If anything, it would have to be b. You can't return a void, but you can return a null. Void on the function declaration should be there to notify the compiler of a lack of a returned value.

Void Type

In C and C++

A function with void result type ends either by reaching the end of the function or by executing a return statement with no returned value. The void type may also appear as the sole argument of a function prototype to indicate that the function takes no arguments. Note that despite the name, in all of these situations, the void type serves as a unit type, not as a zero or bottom type, even though unlike a real unit type which is a singleton, the void type is said to comprise an empty set of values, and the language does not provide any way to declare an object or represent a value with type void.


答:
This whole question is dodgy. The question statement implies the possibility of multiple choices, while the radio buttons indicates a single choice.

Furthermore, b is pretty suspect, as void functions don't return anything.

D is also questionable, for as far as I know, you cannot have an array of functions. Sure, you can have an array of function pointers, but thats not exactly the same thing.

Title: Which one of these answers regarding functions is incorrect?

Body:
So while I've been doing some lengthy compiles I decided to take the C++ general test on ODesk  and came across this question.

If I'm not mistaken, given the wording (or lack thereof) all of these could be true.

a.

```<code>int Foo() { }
int Foo(int bar) { }
</code>```

b.
Well, return void; would be incorrect semantically but functions can obviously have void return types.

```<code>void Foo() { }
</code>```

c. This is the definition of inline functions, yes.

d.
Without going into much detail about the placement of the following elements,

```<code>typedef void (*Func)(int);

Func functions[2];

void Foo(int bar) { }
void Bar(int foo) { }

functions[0] = &Foo;
functions[1] = &Bar;
</code>```

Further, you could always do this using lambdas and functors.

e.

```<code>void Foo(int& bar)
{
    ++bar;
}

int foobar = 5;
Foo(foobar);
</code>```

f.

```<code>int bar = 5;

int& GetBar()
{
    return bar;
}

GetBar() = 6;
</code>```

g.

```<code>int bar = 5;

int* GetBar()
{
    return &bar;
}

(*GetBar()) = 5;
</code>```

I fail to see where this question has any truly false answers. Am I missing something?

Needless to say I ran out of time and failed the whole thing. I guess I'm a bad C++ programmer. :(


问:
How to make C# methods work like javascript functions?
I'll keep it simple, I want to make C#'s methods work like javascript's functions. Mainly so I can convert this -

```<code>function makeVariable(terp) {
    var me = {value: 0};
    return function () { terp.stack.push(me); };
}
</code>```

into C#. Is there ANY way, no matter how complex or time consuming, to do this?

答:
It is entirely possible although you have to be consistent with your types. The technical term for this is closure.</p>

```<code>public Action MakeAction(State s)
{
    var me = new Item();
    return () => s.Stack.Push(me);
}
</code>```

Body:
It is entirely possible although you have to be consistent with your types. The technical term for this is closure.

public Action MakeAction(State s)
{
    var me = new Item();
    return () => s.Stack.Push(me);
}


答:
Answer c) is also arguably false.

"Inline functions are expanded during compile time to avoid invocation overhead."

Firstly, the C++ compiler is permitted to ignore the inline hint by not expanding the functions at all.

Secondly, the stated "reason" for doing expansion is an oversimplification.  In fact, the real reason for doing the expansion (or not) is entirely in the hands of the compiler writer.


问:
Adding field to the class at runtime - design pattern
Imagine your customer want's to have a possibility to add new property (e.g. color) to product in their eshop in their CMS.

Instead of having properties as fields:

```<code>class Car extends Product {
   protected String type;
   protected int seats;
}
</code>```

You would probably end up doing something like:

```<code>class Product {
   protected String productName;
   protected Map<String, Property> properties;
}

class Property {
   protected String name;
   protected String value;
}
</code>```

That is, creating own type system on top of existing one. It feels to me like this could be seen as creating domain specific langauge, or couldn't?

Is this approach a known design pattern? Would you solve the problem differently? I know there are languages where I can add a field in runtime, but what about database? Would you rather add/alter columns or used someting as shown above?

Thank you for your time :).

答:
I like the question, my two cents:

Your two approaches are radically different:

The first one is OO ans strongly typed - but not extensible

The second one is weakly typed (string encapsulates anything)

In C++, many would use a std::map of boost::variant to achieve a mix of both.

Disgression:
Note that some languages, such as C#, allows the dynamic creation of types. Which could be a nice solution for the general issue of adding members dynamically. However, "modifying/adding" types after compilation does corrupt the type system itself, and makes your "modified" types almost useless (e.g., how would you access such added properties, since you dont even know they exists ? The only reasonable way would be a systematic reflection over each object ... ending with a pure dynamic language _ you can refer to the 'dynamic' .NET keyword)


问:
MVC: "User" model gets big and crowded. Should methods that do CRUD operations on one-to-many relationship data be in different models?
In most MVC web projects there is a User class. Many times a user has something else in a one-to-many relationship, i.e. orders.

If we have a user class that has many orders, should methods that add, edit or delete orders for a user be placed in the user class, or in a separate Order class?

i.e.

1.

```<code>user.add_order(order_name)   //Instance method
</code>```

vs

2.

```<code>Order.add_order_for_user(user_id, order_name)   //Static method
</code>```

or alternatively,

3.

```<code>order = new Order(user_id,order_name)
order.save()
</code>```

(Also, in the case of option 3, should this be combined with option 1 and put in that method)?

My main issue with option 1 is that the user model tends to get huge in terms of size. Does this violate SRP? For instance, in one of my projects a user has many "things" like friended users, feeds, uploaded files, warnings, punishments, and the list goes on. I'm basically adding CRUD methods for all those "things" that a particular user has many of, in the User class itself. Is this a bad thing, and should I spread out the CRUD methods to different classes?

However, one of the advantages for option 1 is that I can control logic in those CRUD methods using the attributes of the current user object, without having to query the user. For instance, if I have a method "add_file" I can check to see if the user's total file space used (an attribute of User) is less than a max without having do do another query.

答:
Generally all nouns should have their own class, a model in the case of using the mvc pattern. User and order are two separate things so you should have two models. However, they are related so your data model should have a key or bridge table to relate users with orders.
A user has orders but a user is not updated from an order but more precisely an order record is updated, so you'd want to use the order model for your crud operations.

The problem with scenario 1 is that your code will be tightly coupled to a user.

Also, looks like you should be passing in the order id and user id, not the order name to maintain good practices using proper constraints.


问:
How to learn to make better estimates?
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).

答:
I'm surprised that nobody mentioned the PERT-style estimation technique that is described in Robert Martin's The Clean Coder. In that method, you estimate how long it will take for 3 scenarios: optimistic (O), nominal (N), and pessimistic (P). Then the expected duration = (O+4N+P)/6 and you get a standard deviation of (P-O)/6.

This seems to work pretty well, and I've used it a few times when management really cares about how long something will probably take.

As others have commented, I've also made estimates by examining historical data ("How long did it take to do this similar thing?").

But my favorite method is to not do time estimates at all, and only do point estimates and get a velocity over iterations. If a team is fairly consistent at sizing and completing work (user stories), then you save a ton of time by not even asking how long each thing will take.

Hour estimates are fiendishly hard to get right, and they require a lot of work to break things down into small enough chunks to effectively measure. And even then they're rarely correct because there are too many variables and we forget to account for things like sickness, vacation, or even distractions.

If I have to do hour estimates, I try to only do them for smallish tasks within an iteration. I measure everything in half-day estimates (4, 8, 12 hours) unless I know it could be less. But I rarely estimate anything at less than 1 hour.

Title: How to learn to make better estimates?


答:
c. This is the definition of inline functions, yes.

That is not completely right.

Despite its name, the keyword inline does not guarantee that a function will be inlined. The only thing that you can be sure of is that the compiler will not complain if it sees the definition of an inline function multiple times.

So, strictly speaking, option C is incorrect, but I don't think it is the answer that the authors of the quiz expect, because there is an answer that is even more wrong.

d. Without going into much detail about the placement of the following elements,

```<code>typedef void (*Func)(int);

Func functions[2];

void Foo(int bar) { }
void Bar(int foo) { }

functions[0] = &Foo;
functions[1] = &Bar;
</code>```

Further, you could always do this using lambdas and functors.

In your example, functions is an array of pointers to functions and not an array of functions themselves. Similarly, lambdas and functors are not really functions either. They are classes that respond to the function-call operator, but that doesn't make them functions in the eyes of the C++ language definition.

Functions in C++ are a bit like second-class citizens. You can define and call them, but as soon as you try to do something else with a function type (like create an array of them), you either get an error or they silently convert themselves in a pointer.

Body:
c. This is the definition of inline functions, yes.

That is not completely right.

Despite its name, the keyword inline does not guarantee that a function will be inlined. The only thing that you can be sure of is that the compiler will not complain if it sees the definition of an inline function multiple times.

So, strictly speaking, option C is incorrect, but I don't think it is the answer that the authors of the quiz expect, because there is an answer that is even more wrong.

d. Without going into much detail about the placement of the following elements,

typedef void (*Func)(int);

Func functions[2];

void Foo(int bar) { }
void Bar(int foo) { }

functions[0] = &Foo;
functions[1] = &Bar;

Further, you could always do this using lambdas and functors.

In your example, functions is an array of pointers to functions and not an array of functions themselves. Similarly, lambdas and functors are not really functions either. They are classes that respond to the function-call operator, but that doesn't make them functions in the eyes of the C++ language definition.

Functions in C++ are a bit like second-class citizens. You can define and call them, but as soon as you try to do something else with a function type (like create an array of them), you either get an error or they silently convert themselves in a pointer.


问:
Priority list of tasks stored in a database
I am trying to think of the best way to do the following:

I have a list of tasks stored in the database. A task has a priority assigned to it. You can change the priority of a task to reorder the order they should be carried out.

I am thinking of something very similar to Pivotal Tracker.

So imagine we had the following:

```<code>1 Task A
2 Task B
3 Task C
4 Task D
5 Task E
</code>```

We decide that E is now the most important task

```<code>1 Task E
2 Task A
3 Task B
4 Task C
5 Task D
</code>```

I need to update all 5 tasks to give them a new priority.

If Task B then becomes more important then A I would I would have

```<code>1 Task E
2 Task B
3 Task A
4 Task C
5 Task D
</code>```

I need to update Task B and A only.

What ways would go about structuring this in a DB? I imagine that you would have a differnt projects stored in the same table that would have there own weight.

Would it be better to point a Task that takes place after it (a bit like a link list).

This is just a brain dump really. Just was wondering how you would go about implementing something like this.

答:
If you use double floating point numbers to indicate priority you do not need to re-order:

```<code>1.00 Task A
2.00 Task B
3.00 Task C
4.00 Task D
5.00 Task E
</code>```

If you want to place task E between A and B then:-

```<code>  E.priority = A.priority + ((B.priority - A.priority) / 2)
</code>```

So now you have:

```<code>1.00 Task A
1.50 Task E
2.00 Task B
3.00 Task C
4.00 Task D
</code>```

If you wanted to insert D between E and B then simply set its priority to 1.75.
Given the approximately 18 decimal digits in a floating point number (1.75 is really 1.7500000000000000)  you should have a worst case of 53 consecutive inserts before:

```<code> A.priority + ((B.priority - A.priority) / 2) = B.priority
</code>```

And before anyone complains about the overhead of using doubles vs. integers, its just a few hardware instructions, compared with the processing and I/O overhead of reordering the list in the database which would be several orders of magnitude greater.

Body:
If you use double floating point numbers to indicate priority you do not need to re-order:

1.00 Task A
2.00 Task B
3.00 Task C
4.00 Task D
5.00 Task E

If you want to place task E between A and B then:-

  E.priority = A.priority + ((B.priority - A.priority) / 2)

So now you have:

1.00 Task A
1.50 Task E
2.00 Task B
3.00 Task C
4.00 Task D

If you wanted to insert D between E and B then simply set its priority to 1.75.
Given the approximately 18 decimal digits in a floating point number (1.75 is really 1.7500000000000000)  you should have a worst case of 53 consecutive inserts before:

 A.priority + ((B.priority - A.priority) / 2) = B.priority

And before anyone complains about the overhead of using doubles vs. integers, its just a few hardware instructions, compared with the processing and I/O overhead of reordering the list in the database which would be several orders of magnitude greater.


答:
If your case is order processing which is focusing in orders, then I believe Order is the root aggregate entity that has a reference to User entity, for example:

```<code>class Order {

   User user

   Payment payment

   Delivery delivery

   ...
}
</code>```

If you want to select Order based on User, you can create new methods in your repository such as:

```<code>interface OrderRepository {

   public List<Order> findOrderByUser(User user);

   public List<Order> findOrderByUserAndStatus(User user, OrderStatus status);

}
</code>```

If you have business logic that requires some calculations in User based on Order, you can add required Order to User.  Usually it is not all Order that has been created by that user (your concern is they are too many to store in User, right?).  For example, it can be pendingOrder:

```<code>class User {

    List<PendingOrder> pendingOrders = []

    BigDecimal creditLimit

    boolean allowNewOrder() {
       ...  // check if sum of pendingOrders is not more than allowed limit
    }
}
</code>```

I believe this will make your domain classes richer.

Title: MVC: "User" model gets big and crowded. Should methods that do CRUD operations on one-to-many relationship data be in different models?

Body:
In most MVC web projects there is a User class. Many times a user has something else in a one-to-many relationship, i.e. orders.

If we have a user class that has many orders, should methods that add, edit or delete orders for a user be placed in the user class, or in a separate Order class?

i.e.

1.

```<code>user.add_order(order_name)   //Instance method
</code>```

vs

2.

```<code>Order.add_order_for_user(user_id, order_name)   //Static method
</code>```

or alternatively,

3.

```<code>order = new Order(user_id,order_name)
order.save()
</code>```

(Also, in the case of option 3, should this be combined with option 1 and put in that method)?

My main issue with option 1 is that the user model tends to get huge in terms of size. Does this violate SRP? For instance, in one of my projects a user has many "things" like friended users, feeds, uploaded files, warnings, punishments, and the list goes on. I'm basically adding CRUD methods for all those "things" that a particular user has many of, in the User class itself. Is this a bad thing, and should I spread out the CRUD methods to different classes?

However, one of the advantages for option 1 is that I can control logic in those CRUD methods using the attributes of the current user object, without having to query the user. For instance, if I have a method "add_file" I can check to see if the user's total file space used (an attribute of User) is less than a max without having do do another query.

Body:
If your case is order processing which is focusing in orders, then I believe Order is the root aggregate entity that has a reference to User entity, for example:

class Order {

   User user

   Payment payment

   Delivery delivery

   ...
}

If you want to select Order based on User, you can create new methods in your repository such as:

interface OrderRepository {

   public List<Order> findOrderByUser(User user);

   public List<Order> findOrderByUserAndStatus(User user, OrderStatus status);

}

If you have business logic that requires some calculations in User based on Order, you can add required Order to User.  Usually it is not all Order that has been created by that user (your concern is they are too many to store in User, right?).  For example, it can be pendingOrder:

class User {

    List<PendingOrder> pendingOrders = []

    BigDecimal creditLimit

    boolean allowNewOrder() {
       ...  // check if sum of pendingOrders is not more than allowed limit
    }
}

I believe this will make your domain classes richer.


问:
options for data analytics for time series store
I'm building an Internet of Things solution that has a number of real time feeds. I need to make a couple of design decisions with regards to the data store and reporting and looking for input.

I have two deployment models, local where a small Linux server captures multiple streams usually a new data point each second and record length is small, basically a fixed format message of about 20 bytes. The other model is cloud based where the transaction rate will be much higher, up to 1000 data points a second.

Concentrating on the local model first, my prototype uses SQLite under MONO and works fine in a traditional RDMS manner. However I'm aware that RDBMS isn't optimal for time series systems and possibly a NOSQL solution might be better.

I'm having a re-think on the SQL approach due to my real time analytics requirement. I want to be able to easily report on SUM, COUNT, AVERAGE, MEAN, SD, MIN, MAX on potentially each of the time series datasets, basically have the system recalculate these for each new data point. Although I haven't done any performance testing, I can see if I have a year or more data the dataset size is going to be pretty large (20 bytes / second over a year is 600MB and I could have up to 30 different time series datasets) and won't be great for real time calculation of averages etc. in normal SQL. I also want to keep the size / cost of the server low so won't be able to add gobs of CPU or memory but disk space should be OK.

The other option I have is that my system can store the delta (changes) to the real time feeds instead of the regular data point, which will save about 80% of the disk space. However I don't know of an easy way to do set calculations like running averages if I am storing deltas (as far as I know not possible with standard SQL statements but I could be wrong).

Given my use case above I have 3 questions:

1) Should I seriously consider a NOSQL data store? Do you have any suggestions on the advantages of a NOSQL store for this model?

2) How I can best do real time set calculations like average without a lot of complexity or hardware? I have platform options of either MONO or NODE on Linux or Windows.

3) How to do efficient real time set calculations (especially averages which will be the majority of calculations) on either SQLite or a NOSQL DB when I'm storing deltas?

答:
NoSQL

For your raw transactions, if the data you are getting is not required to follow a specific format, NoSQL may be a good way to store the data. If it is capable of being stored in a relational data model easily (tables and columns), there are significant speed advantages to using a relational database.

How to do efficient calculations

Aggregate based on a time period

One of the fastest things you can do is to aggregate your data over a time period, storing the results.

Let's assume that your real time feeds are by the minute. That would be 1,440 data points per day, 10,080 per week, approximately 43,000 per month, or 525,600 per year. Now, cut that down to one record per day. That would be a savings of 525,236 records per year. It is also over half a million rows that you don't have to aggregate every time you need to perform a "real time" calculation. You will have to determine what the smallest time period is for a meaningful aggregation that isn't excessively large or small.

A concrete example will help to illustrate this principle: stock market trades by ticker symbol. Every trade comes across the wire with the ticker symbol, the time of the trade, price per share, and quantity of shares traded. There may be other data in the feed, but this will suffice for the example. Knowing the high (max), low (min), and average (mean) of all the trades by day will show certain types of trends. It is not necessary to see the individual transactions when you are looking for a trend that is days, months, or even years in the making. Once you have aggregated that data for the previous day's raw transactions, you don't ever need to recalculate those items again. Store the aggregated data in another table. Then if you want to determine an average (mean) price for a specific ticker over a period of time (week, month, quarter, etc.), it is a fairly simple SQL statement with a date range.

Weighted aggregation

Another very fast method you can use is commonly known as weighted averages.

Simply put, this is a running aggregation where you have a your aggregated value multiplied by a weight (often a total quantity), add your new value, and then divide by the weight + the new weight. This is easier than it sounds.

If you have an average price per share for the day (going back to the stock market example above), you can average the price by transaction (sum(price) / number of transactions). This would be one method for performing the averaging.

To make the average of a weighted average equal that of a standard average, you have to multiply the current average by the number of transactions that have already completed.

The weighted average method will have you keep a running average of the price and the number of transactions. When a new transaction comes in, the previous average price is multiplied by the number of transactions, added to the new transaction price, and finally divided by the number of transactions + 1. If you had 10 transactions at an average price of $20 and a new trade comes in with a price of $24, your weight average would be $20.37 ((10 <-- number of transactions * 20 <-- average price ) + 24 <-- new trade price ) / 11 <-- new number of transactions. When the next trade comes in at $25, your weighted average would be $20.76 ((11 <-- number of transactions * 20.37 <-- average price ) + 25 <-- new trade price ) / 12 <-- new number of transactions.


问:
Categorize tasks/bugs by risk of changes
The project I'm currently working on has an issue: bugs and tasks are often assigned to people who are too new or too inexperienced and their work ends up producing more bugs down the road. The problem is that parts of our software are much more "dangerous" to work on than others due to code quality issues. I've been trying to combat this issue by estimating the risk associated with tasks and paying close attention to which developers get assigned which tasks.

We use JIRA so I started labeling issues to keep track of this estimation. I've noticed that I've ended up using several metrics to categorize a bug/task:

How clear/straightforward it is. E.g. whether it's something that will need a lot of design work or just a simple UI bug fix.

How maintainable the affected area of the code is. Is it a well-designed area or a big ball of mud.

How much of the program I think will be affected by the required change.

My labels are kind of messy since I didn't have a clear idea when I started what the possible categories would be and I still don't. I'm thinking about requesting a new field be added (something like "Risk") so that we can require an estimate before assigning the work to someone.

Has anyone dealt with this sort of thing before?

答:
I would say that what you are referring to here could better be called 'complexity'. Of course, the more complex a change is the higher the 'risk' is that some new bug may be introduced by an inexperienced programmer. It is not a bad idea to introduce such a field if it is a real issue.

However, judging from what you wrote you seem to have two issues:

You are dealing with new or inexperienced programmers.

The quality of (much/some) of your code seems to be questionable.

In addition to introducing something like a 'complexity' field (which would help to manage and prioritize your work), I would suggest you focus on mitigating the risk of the above two issues.

To address the first issue I would create a process whereby new programmers first discuss all new bugs with a more experienced programmer before working on the bug. Also, I will definitely introduce code reviews to both lower the risk of new bugs being introduced and to use as coaching opportunity for the new programmers to get up to speed more quickly.

With respect to code quality, I would do two things. Firstly, stop the rotting process: agree on coding standards and practices that would prevent any new inferior code from being introduced. The suggested code reviews would help here too. Secondly, I would identify the worst parts of your code and start refactoring and cleaning up these.


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
I can't decide whether some answers on this thread are hilarious or serious: cookies more dangerous than javascript ? LOL

Any site should be tested with js and cookies turned off however, it's a minimum imho.