问:
Is catching general exceptions really a bad thing?
I typically agree with most code analysis warnings, and I try to adhere to them. However, I'm having a harder time with this one:

CA1031: Do not catch general exception types

I understand the rationale for this rule. But, in practice, if I want to take the same action regardless of the exception thrown, why would I handle each one specifically? Furthermore, if I handle specific exceptions, what if the code I'm calling changes to throw a new exception in the future? Now I have to change my code to handle that new exception. Whereas if I simply caught Exception my code doesn't have to change.

For example, if Foo calls Bar, and Foo needs to stop processing regardless of the type of exception thrown by Bar, is there any advantage in being specific about the type of exception I'm catching?

Maybe a better example:

```<code>public void Foo()
{
    // Some logic here.
    LogUtility.Log("some message");
}

public static void Log()
{
    try
    {
        // Actual logging here.
    }
    catch (Exception ex)
    {
        // Eat it. Logging failures shouldn't stop us from processing.
    }
}
</code>```

If you don't catch a general exception here, then you have to catch every type of exception possible. Patrick has a good point that OutOfMemoryException shouldn't be dealt with this way. So what if I want to ignore every exception but OutOfMemoryException?

答:
I have been pondering the same recently, and my tentative conclusion is that the mere question arises because the .NET Exception hierarchy is severely messed up.

Take, for example, the lowly ArgumentNullException which might be a reasonable candidate for an exception you don't want to catch, because it tends to indicate a bug in the code rather than a legitimate runtime error. Ah yes. So does NullReferenceException, except that NullReferenceException does derive from SystemException directly, so there's no bucket you can place all "logical errors" into to catch (or not catch).

Then there is the IMNSHO major botch of having SEHException derive (via ExternalException) SystemException and thus make it a "normal" SystemException When you get an SEHException, you want to write a dump and terminate as fast as you can -- and starting with .NET 4 at least some SEH exceptions are considered Corrupted State Exceptions that will not be caught. A good thing, and a fact that makes the CA1031 rule even more useless, because now your lazy catch (Exception) will not catch these worst types anyway.

Then, it seems that the other Framework stuff rather inconsistently derives either Exception directly or via SystemException, making any attempt at grouping catch-clauses by something like severity moot.

There's a piece by Mr. Lippert of C# fame, called Vexing Exception, where he lays out some useful categorization of exceptions: You could argue you only want to catch "exogenous" ones, except ... C# the language and the design of the .NET framework exceptions make it impossible to "catch only exogenous ones" in any succinct manner. (and, e.g, an OutOfMemoryException may very well be a totally normal recoverable error for an API that has to allocate buffers that are somehow large)

Bottom line for me is, that the way C# catch blocks work and the way the Framework exception hierarchy is designed, rule CA1031 is beyond totally useless. It pretends to help with the root issue of "do not swallow exceptions" but swallowing exceptions has zero to do with what you catch, but with what you then do:

There are at least 4 ways to legitimately handle a caught Exception, and CA1031 only seems to superficially handle one of them (namely the re-throw case).

As a side note, there's a C# 6 feature called Exception Filters that will make CA1031 slightly more valid again since then you will be able to properly, properly, properly filter the exceptions you want to catch, and there's less reason to write an unfiltered catch (Exception).


问:
Going from cutting edge to maintaining legacy projects
I have an Access 03 program with a bunch of VBA code that is in use and the end user wants new functionality. I am finding it very difficult to add new functionality because my brain wants to use the most recent .NET technologies and VBA is not recent at all.

How should I go about "rolling back" technologies in my head to keep my frustration levels to a minimum?

Also my boss said it wasn't in the budget to rewrite the project from access and vba to some sort of form and SQL combo (which I could probably pound out in a few days, which is the same amount of time that I feel that it will take me to look up and implement in the old system).

答: If you're good at what you do and it's your professional opinion that it would be more cost-effective to re-do it in .NET instead of struggle with VBA, then your boss should take that seriously.  If they don't then I recommend you find a new, competent boss somewhere else :)</p>

ContentLicense: CC BY-SA 2.5


问:
Python recipe question: Use of **kwds instead of specific named argument in itertools recipe
The function definition below comes from the itertools recipes page
(https://docs.python.org/2/library/itertools.html#recipes).

```<code>def random_product(*args, **kwds):
    "Random selection from itertools.product(*args, **kwds)"
    pools = map(tuple, args) * kwds.get('repeat', 1)
    return tuple(random.choice(pool) for pool in pools)
</code>```

The function signature would seem to be more readable written with the "repeat" argument specified explicitly, e.g.

```<code>def random_product(*args, repeat=1)
</code>```

But I'm guessing there is a reason why it is written using the general idiom.  Can anyone explain?

答:
In Python 2, you cannot put a keyword argument after *args, that's a syntax error:

```<code>>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=8, releaselevel='final', serial=0)
>>> def random_product(*args, repeat=1):
  File "<stdin>", line 1
    def random_product(*args, repeat=1):
                                   ^
SyntaxError: invalid syntax
</code>```

If you put it before the positional catch-all, then it captures the first positional argument:

```<code>>>> def random_product(repeat=1, *args): return repeat, args
...
>>> random_product('foo', 'bar')
('foo', ('bar',))
</code>```

In Python 2 then, your only option is to capture arbitrary keyword arguments with **kw (since that only ever captures actual keyword arguments, not positional arguments), and extract repeat from that.

Python 3 adjusted what is supported; there any keyword arguments specified after the *args catch-all are allowed and are seen as keyword-only:

```<code>>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=4, micro=1, releaselevel='final', serial=0)
>>> def random_product(*args, repeat=1):  return args, repeat
...
>>> random_product('foo', 'bar')
(('foo', 'bar'), 1)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In Python 2, you cannot put a keyword argument after *args, that's a syntax error:

>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=8, releaselevel='final', serial=0)
>>> def random_product(*args, repeat=1):
  File "<stdin>", line 1
    def random_product(*args, repeat=1):
                                   ^
SyntaxError: invalid syntax

If you put it before the positional catch-all, then it captures the first positional argument:

>>> def random_product(repeat=1, *args): return repeat, args
...
>>> random_product('foo', 'bar')
('foo', ('bar',))

In Python 2 then, your only option is to capture arbitrary keyword arguments with **kw (since that only ever captures actual keyword arguments, not positional arguments), and extract repeat from that.

Python 3 adjusted what is supported; there any keyword arguments specified after the *args catch-all are allowed and are seen as keyword-only:

>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=4, micro=1, releaselevel='final', serial=0)
>>> def random_product(*args, repeat=1):  return args, repeat
...
>>> random_product('foo', 'bar')
(('foo', 'bar'), 1)


问:
Class design - should methods call other methods?
I'm writing a very basic custom class for coupons and I've come up with a basic layout for the class, which consists of a number of small methods as I generally understand is a best practice.

What I'm unsure of is how the flow of a class should be dictated. Right now the code looks something like this:

```<code>public function isCouponValid($coupon) {
    if (strlen($coupon) != 8) return false;

    $query = $this->db->prepare('SELECT coupon_code FROM coupons WHERE coupon_code=:coupon');
    try ($query->execute(array(':coupon' => $coupon))) {
        while ($row = $query->fetch()) {
            return true;
        }
    } catch (PDOException $e) {
        $log->addError('Could not execute SQL query: '.$query.' '.$e->getMessage());
    }

    return false;
}

public function isCouponUsed($coupon) {
    if (self::isCouponValid($coupon)) {
        $query = $this->db->prepare('SELECT coupon_used FROM coupons WHERE coupon_code=:coupon');
        try ($query->execute(array(':coupon' => $coupon))) {
            while ($row = $query->fetch()) {
                return ($row['coupon_used'] == '1') ? true : false;
            }
        } catch (PDOException $e) {
            $log->addError('Could not execute SQL query: '.$query.' '.$e->getMessage());
        }
    }

    return false;
}

public function setCouponUsed($coupon) {
    if (self::isCouponValid($coupon) && !self::isCouponUsed($coupon)) {
        etc...
    }
}
</code>```

Basically I have these checks integrated into the class right now - isCouponUsed() calls isCouponValid() in order to check that it's valid first. Is this a good idea, or is it better for me to use isCouponValid() outside of the class and then pass that value to isCouponUsed(), such that isCouponUsed() should just be concerned with validating a coupon and not check if that code is valid first?

答:
Basically I have these checks integrated into the class right now -
  isCouponUsed() calls isCouponValid() in order to check that it's valid
  first. Is this a good idea, or is it better for me to use
  isCouponValid() outside of the class and then pass that value to
  isCouponUsed(), such that isCouponUsed() should just be concerned with
  validating a coupon and not check if that code is valid first?

A method calling other methods to perform its job is fine and fits well into object orientated design. Think of objects as people that perform a behavior in the system. The less an individual person has to do the smoother the system will work.

Imagine you ring a call center to order a new phone. You talk to a customer facing "object", but that "object" might query a whole host of other objects internal to the systems in order to carry out the behavior of "provide customer with new phone". As an external customer you don't see or care about any of that, but the call centre would fall a part if the guy on the phone also had to check inventory, run to the warehouse to fetch the phone, parcel it, post it etc.

Likewise if a coupon needs to first check if it is valid before checking if it is used that is fine. The external object that sent the message "are you valid" to the coupon object doesn't care what it does in order to perform this action, but separating out responsibility to a number of smaller object with clear behavior is good design (in the same way that the guy who answers the phone in the call centre doesn't perform every action involved in getting you a new phone, that would be silly)

Your code might make more sense if you moved the methods into the coupon object. Why can't the coupon validate itself, and track if it is used itself. You will probably greatly reduce the number of public methods on the object.


问:
Saving an object via a method of its own or via another class?
If I want to save and retrieve an object, should I create another class to handle it, or would it better to do that in the class itself? Or maybe mixing both?

Which is recommended according to OOD paradigm?

For example

```<code>Class Student
{
    public string Name {set; get;}
    ....
    public bool Save()
    {
        SqlConnection con = ...
        // Save the class in the db
    }
    public bool Retrieve()
    {
         // search the db for the student and fill the attributes
    }
    public List<Student> RetrieveAllStudents()
    {
         // this is such a method I have most problem with it
         // that an object returns an array of objects of its own class!
    }
}
</code>```

Versus. (I know the following is recommended, however it seems to me a bit against the cohesion of Student class)

```<code>Class Student { /* */ }
Class DB {
  public bool AddStudent(Student s)
  {

  }
  public Student RetrieveStudent(Criteria)
  {
  }
  public List<Student> RetrieveAllStudents()
  {
  }
}
</code>```

How about mixing them?

```<code>   Class Student
    {
        public string Name {set; get;}
        ....
        public bool Save()
        {
            /// do some business logic!
            db.AddStudent(this);
        }
        public bool Retrieve()
        {
             // build the criteria
             db.RetrieveStudent(criteria);
             // fill the attributes
        }
    }
</code>```

答:
Both approaches violate the Single Responsibility Principle. You first version gives the Student class to many responsibilities and ties it to a specific DB access technology. The second leads to a huge DB class which will be responsible not just for students, but for any other kind of data object in your program. EDIT: your third approach is the worst, since it creates a cyclic dependency between the DB class and the Student class.

So if you are not going to write a toy program, use none of them. Instead, use a different class like a StudentRepository for providing an API for loading and saving, assumed you are going to implement the CRUD code on your own. You might also consider to use an ORM framework, which can do the hard work for you (and the framework will typically enforce some decisions where the Load and Save operations have to be placed).


答:
There are quite a few patterns that can be used for data persistence. There is the Unit of Work pattern, there is Repository pattern, there are some additional patterns that can be used like the Remote Facade, and so on and on.

Most of those have their fans and their critics. Often it comes to picking what seems to suit the application best and sticking with it (with all its upsides and downsides, i.e. not using both patterns at the same time... unless you're really sure about that).

As a side note: in your example the RetrieveStudent, AddStudent should be static methods (because they are not instance-dependant).

Another way of having in-class save/load methods is:

```<code>class Animal{
    public string Name {get; set;}
    public void Save(){...}
    public static Animal Load(string name){....}
    public static string[] GetAllNames(){...} // if you just want to list them
    public static Animal[] GetAllAnimals(){...} // if you actually need to retrieve them all
}
</code>```

Personally I'd use such approach only in a fairly small applications, possibly tools for personal use or where I can reliably predict that I won't have a more complicated use cases than just saving or loading objects.

Also personally, see the Unit of Work pattern. When you get to know it, it is really good in both small and large cases. And it is supported by a lot of frameworks/apis, to name EntityFramework or RavenDB for example.

Title: Saving an object via a method of its own or via another class?

Body:
If I want to save and retrieve an object, should I create another class to handle it, or would it better to do that in the class itself? Or maybe mixing both?

Which is recommended according to OOD paradigm?

For example

```<code>Class Student
{
    public string Name {set; get;}
    ....
    public bool Save()
    {
        SqlConnection con = ...
        // Save the class in the db
    }
    public bool Retrieve()
    {
         // search the db for the student and fill the attributes
    }
    public List<Student> RetrieveAllStudents()
    {
         // this is such a method I have most problem with it
         // that an object returns an array of objects of its own class!
    }
}
</code>```

Versus. (I know the following is recommended, however it seems to me a bit against the cohesion of Student class)

```<code>Class Student { /* */ }
Class DB {
  public bool AddStudent(Student s)
  {

  }
  public Student RetrieveStudent(Criteria)
  {
  }
  public List<Student> RetrieveAllStudents()
  {
  }
}
</code>```

How about mixing them?

```<code>   Class Student
    {
        public string Name {set; get;}
        ....
        public bool Save()
        {
            /// do some business logic!
            db.AddStudent(this);
        }
        public bool Retrieve()
        {
             // build the criteria
             db.RetrieveStudent(criteria);
             // fill the attributes
        }
    }
</code>```

Body:
There are quite a few patterns that can be used for data persistence. There is the Unit of Work pattern, there is Repository pattern, there are some additional patterns that can be used like the Remote Facade, and so on and on.

Most of those have their fans and their critics. Often it comes to picking what seems to suit the application best and sticking with it (with all its upsides and downsides, i.e. not using both patterns at the same time... unless you're really sure about that).

As a side note: in your example the RetrieveStudent, AddStudent should be static methods (because they are not instance-dependant).

Another way of having in-class save/load methods is:

class Animal{
    public string Name {get; set;}
    public void Save(){...}
    public static Animal Load(string name){....}
    public static string[] GetAllNames(){...} // if you just want to list them
    public static Animal[] GetAllAnimals(){...} // if you actually need to retrieve them all
}

Personally I'd use such approach only in a fairly small applications, possibly tools for personal use or where I can reliably predict that I won't have a more complicated use cases than just saving or loading objects.

Also personally, see the Unit of Work pattern. When you get to know it, it is really good in both small and large cases. And it is supported by a lot of frameworks/apis, to name EntityFramework or RavenDB for example.


答:
Single Responsibility Principle, Separation of Concerns and Functional Cohesion. If you read up on these concepts, the answer you get is: Separate them.

A simple reason to separate the Student from the "DB" class (or StudentRepository, to follow more popular conventions) is to allow you to change your "business rules", present in the Student class, without affecting code that is responsible for persistence, and vice-versa.

This kind of separation is very important, not only between business rules and persistence, but between the many concerns of your system, to allow you to make changes with minimal impact in unrelated modules (minimal because sometimes it is unavoidable). It helps to build more robust systems, that are easier to maintain and are more reliable when there are constant changes.

By having business rules and persistence mixed together, either a single class as in your first example, or with DB as a dependency of Student, you're coupling two very different concerns. It may look like they belong together; they seem to be cohesive because they use the same data. But here's the thing: cohesion cannot be measured solely by the data that is shared among procedures, you must also consider the level of abstraction at which they exist. In fact, the ideal type of cohesion is described as:

Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module.

And clearly, performing validations about a Student while also persisting it do not form "a single well-defined task". So again, business rules and persistence mechanisms are two very different aspects of the system, which by many principles of good object oriented design, should be kept separate.

I recommend reading about Clean Architecture, watching this talks about Single Responsibility Principle (where a very similar example is used), and watching this talk about Clean Architecture as well. These concepts outline the reasons behind such separations.


问:
How can I test my application for load balancing?
We are looking to implement a load balancer that will serve requests between 2 IIS servers.

I have been tasked with the project of making sure that it is a seamless integration, but I don't have load balancing myself on my dev machine.

How can I simulate a round-robin load balancing scenario on my dev system using IIS?

答:
If you want to test a specific server setup, you need to have a comparable setup available with which you can test.

This is probably the time to look at adding some sort of test environment to your setup.

This would allow you to retain a simple local development environment without load balancing that you can test your code on. Then, when you have a stable release candidate you can move it to the test environment, which would be load balanced. In this sort of setup, each developer would have their own development environment, but would all share a test environment which can act as a clean setup to prevent the idiosyncrasies of one workstation from creating or obscuring bugs.

If you are truly determined to have your own load balancing system, you may want to look at setting up two or three virtual machines (via Virtual PC, VirtualBox or VMWare) and running them locally. You could then configure these VMs to be load balanced amongst one another and test against them.


问:
Enumerated types and their interpretation by compilers
It seems to me that a lot, if not most, compilers treat enumerated types as int underneath. In C/gcc, enums are compiled to int. In C#/Visual C#, you can change the underlying data type with something like:

```<code>enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
</code>```

but the default is int (second paragraph) if you don't change the type.

For obvious reasons, ints are efficient. They fly through the ALU with ease and avoid useless string comparisons.

Upon first glance, it doesn't seem that interpreted languages have enumerated types built-in (Ruby, Perl, JavaScript, others I'm sure). They can be emulated though; i.e. in JavaScript.

My questions:

Why do (seemingly) most compilers use int as the underlying type? Is the reason historical/performance-related?

Are there languages that compile enumerated types to something other than int (or byte, long, numerical types...)? If so, why did they choose to do it differently?

答:
I'll try to shed some light based on languages I'm most familiar with:

D:

Enumerators in the D language are just another way of declaring compile-time constants. They are are very flexible and allow enums of string type, which is not very usual. Control of the size of integer constants is also possible. See the bottom of the page in the previous link for several examples.

C++:

Old-style unscoped enums in C++ are not required to have the size of a C++ int object. They can be larger than that. Quoting this reference:

an unscoped enumeration type whose underlying type is not fixed ... in
  this case, the underlying type is either int or, if not all
  enumerator values can be represented as int, an
  implementation-defined larger integral type that can represent all
  enumerator values.

So if we compare the size of these two C++ enumerators:

```<code>enum Test1 {
    A1,
    B1
};
enum Test2 {
    A2,
    B2 = 18446744073709551615ULL /* UINT64_MAX */
};
</code>```

The first one will be the size of a default integer (int) and the second, the size of a 64bit integer (long long int) to fit the large constant.

The new enum class introduced in C++11 allows the user to specify the size of the enum type and its constants. The constants are also scoped. They are very similar to a C# enumerator.

Why are integers the common case?

I'll speculate that integers are commonly the default choice for enumerator types in programming languages because of simplicity. The machine can only really deal with numbers. Even a text string is just and array of numbers interpreted in a special way by the program.

Body:
I'll try to shed some light based on languages I'm most familiar with:

D:

Enumerators in the D language are just another way of declaring compile-time constants. They are are very flexible and allow enums of string type, which is not very usual. Control of the size of integer constants is also possible. See the bottom of the page in the previous link for several examples.

C++:

Old-style unscoped enums in C++ are not required to have the size of a C++ int object. They can be larger than that. Quoting this reference:

an unscoped enumeration type whose underlying type is not fixed ... in
  this case, the underlying type is either int or, if not all
  enumerator values can be represented as int, an
  implementation-defined larger integral type that can represent all
  enumerator values.

So if we compare the size of these two C++ enumerators:

enum Test1 {
    A1,
    B1
};
enum Test2 {
    A2,
    B2 = 18446744073709551615ULL /* UINT64_MAX */
};

The first one will be the size of a default integer (int) and the second, the size of a 64bit integer (long long int) to fit the large constant.

The new enum class introduced in C++11 allows the user to specify the size of the enum type and its constants. The constants are also scoped. They are very similar to a C# enumerator.

Why are integers the common case?

I'll speculate that integers are commonly the default choice for enumerator types in programming languages because of simplicity. The machine can only really deal with numbers. Even a text string is just and array of numbers interpreted in a special way by the program.


问:
Using reflection vs creating a new class
I and a friend are having an argument on what is the better technique to use in the following scenario:

An application we need to test has a number of components (lets call them Eggs); each component is a bag of predefined sub-components. These components are the input to our application, there is no way we can change/annotate these components at their source.

Now, we have a set of validators for each sub-component. It is not programatically possible to associate an Egg with its validators, so it has to be done manually for each new Egg (there are a finite number of eggs). Once the mapping is done, we can run each validator for each Egg to see if the Egg is good or rotten.

Now, my way of doing it is to have a config file which consists of the mapping between each Egg and its validators. Eg:

```<code>{
  Egg1: [validator1, validator2]
  Egg2: [validator5, validator7, validator2]
}
</code>```

Now we can read this file and use reflections to select the appropriate validator (from the list of all classes implementing IValidator) for each Egg.

My friend is averse to using reflections, and prefers to add a new C# class for each Egg everytime a new type of Egg is added. The class represents the Egg and runs the appropriate validators for that Egg.

Which way is better? I prefer the reflections method because everytime a new type of Egg shows up all we need to do is edit the config.

To clarify, an Egg is a selection from predefined list of sub-components. Assume that there will be no more sub-components, and hence there is no need for new validators. We cannot enumerate all possible Eggs because there are too many.

答:
Which way is better?

Based on what you've described, adding a new class is way better.

why?

Because editing a config is just as hard/painful as editing code, except it's tons more error prone and requires more work to setup - and nobody coming into your company knows what the hell this config is, or what format it's in, or where to find it.

Now, if you could use reflection to inspect the Eggs and see what sub-components they have (and you don't have significant performance requirements), that seems like an even better solution...


问:
Why not use the word bug instead of exception?
If we refer to exceptions as bugs, why not just call it a bug in the first place instead of an exception?

If in the code it's called exception and as soon as it occurs it's called a bug. Then why not call it a bug in the first place?

Thank you for any answer or comment.

答:
Since this question has been re-opened for a bounty, let me mention my CUJ article from 2003 entitled "An Exception or a Bug?", which seems to address exactly the OP's question.

Basically, the article defines the terms "bug" and "exception" (giving examples), and proposes strategies for dealing with each.

The article proposes not to "handle" bugs but instead flag them with assertions. In contrast, true exceptions require handling through code (possibly throwing/catching exceptions).

The main point is that bugs require the exact opposite strategy than exceptions.

The aforementioned article is available now from Dr.Dobb's at:
http://www.drdobbs.com/an-exception-or-a-bug/184401686


答:
As Michael says, you need to set up a test environment that mirrors your intended deployment environment.

Traditionally this was done in-house. That option is still open to you, and will give you the most control over the test resources.  But testing is a near-perfect scenario for cloud servers. Whether you rent them from Amazon, GoGrid, HP, Rackspace, or someone else, you can set up test environments--including servers, simulated clients, load balancers, etc. that you will pay for only for the duration of your tests. While there are some hurdles in matching the cloud test configuration to the configuration you'll have in deployment, the advantages can be substantial:

Low cost. You only pay the infrastructure cost for the duration of the setup and test.

High scale. You can afford to run much larger tests with many more clients, much higher load, and much higher scale points that you could probably afford for test infrastructure you buy and bring in-house.

Title: How can I test my application for load balancing?

Body:
We are looking to implement a load balancer that will serve requests between 2 IIS servers.

I have been tasked with the project of making sure that it is a seamless integration, but I don't have load balancing myself on my dev machine.

How can I simulate a round-robin load balancing scenario on my dev system using IIS?


问:
For in-house programmers (non-project managers), do you normally receive project instructions written out in advance?
I'm fairly new to working as a programmer, at least working as a regular employee in-house for a company. I often become frustrated with my company's management style as they basically just pick out whatever random tasks catches the lead developer's fancy that day, or the day before, and give me the task (with tasks usually lasting less than 1 day). A lot of the tasks I have now are fairly small and are for adding enhancements to a web application, fixing bugs, etc.

I am bothered, however, by the fact that they don't plan ahead so as to give me an written outline of projects a few days in advance so that if, for example, I am rusty on something I can at least familiarize myself with it on my own time or at least have a more relaxed approach to the job so that everything doesn't have to be so reactionary on my part (where I can mull things during off-time over before starting work on them, etc)

I guess I'm just curious if this is the norm or if most development jobs value clearly laid out specifications for tasks and are able to prepare them somewhat in advance. I would be interested to hear anyone's experience / opinions, etc. Thanks

答:
No, what you have is rather rare in my experience.  Scrums tend to allow some flexibility in knowing what is coming up as the sprint has a defined set of work that is to be during it as there are planning meetings where the team decides, "This is what will get done during the next sprint."  That does tend to prevent the, "Oh get this done NOW!" kind of dramatics usually and give some bounds on where the focus is during a sprint.  Typically, things aren't written out well and so clarifying what is requested and how much time should be spent are a couple of factors to consider with things.  For example, some bugs one could spend days getting all the cases covered thoroughly while some may accept the work that can get done in a couple of hours that covers 99% of the cases that will often happen.

To take a devil's advocate position about not knowing what is coming soon, would you really want to be told one thing only to have it changed a few days later when you were just about to start working on it?  I mean imagine if you thought you'd get to work on feature X but instead support request Y takes priority and that wasn't reported until late yesterday so there wasn't a lot of time to tell you about this change until now.


问:
Track a series of choices with a single number
I want to track a series of scored questions in a single number (the total score). Is that possible? and how?

For example, I have 30 questions with either 3 or 2 choices. For any given question, the user makes a selection and the score is incremented/decremented. Simple addition and subtraction is enough for that, but I want to also be able to go back and determine what they answered for any question.

My first thought is that this is some checksum operation or using some modula/shift operations (masking). So there could be a number of inputs such as the choice, question number, user number, etc.

Update: removed int preference as its unreasonable and lowered the number of questions.

答:
An int represents a fixed number of bits (usually 32 or 64). This is a measure of information content; it is fundamentally impossible to store more than this number of yes/no decisions in it. With three-way decisions the arithmetic becomes slightly more involved because they represent fractional numbers of bits (two three-way questions contain slightly more information than three two-way questions), but the principle remains.

Therefore using scalar values this way is a bad idea. It's fragile (as soon as your questionnaire grows above the magic number of steps, it breaks), and even while it works, it's expensive to encode and decode the information you actually want from the value it's stored in. The question therefore becomes: Why do you want to use an int? Are you sure structured data of some kind aren't an easier and better choice?


答:
You can store the value as a number if you have a datatype that can represent more than choicescount possible values.  In the case of 340, this is the number 12,157,665,459,056,928,801 which is just under 64 bits.  So, you could hypothetically store this in a Unit64 (docs).

This isn't a good idea.

As soon as you add another question, you will overflow this datatype.  That will make life very difficult for refactoring.

You've got something that isn't quite binary.  This makes a mess of trying to decode it with binary operators.  You can do it, but its very ugly.

If anything changes (you remove a question) it becomes very fragile.  It is easy to break this.

These things combined should firmly point you in the direction of a list of three value enums which can then be serialized.  Don't worry about a specific number.  Make it a nice structure that you can work from and then convert that into however you want to transmit it.  When storing it in a database or the like, store it as a nice structure (not a big number).

Trying to pack things into bits doesn't make sense anymore.  Memory is cheap.  Its easier to transmit a 40 character long string that contains [ynm] that you an work with - clean code that you can reason about without getting a headache.

Title: Track a series of choices with a single number

Body:
I want to track a series of scored questions in a single number (the total score). Is that possible? and how?

For example, I have 30 questions with either 3 or 2 choices. For any given question, the user makes a selection and the score is incremented/decremented. Simple addition and subtraction is enough for that, but I want to also be able to go back and determine what they answered for any question.

My first thought is that this is some checksum operation or using some modula/shift operations (masking). So there could be a number of inputs such as the choice, question number, user number, etc.

Update: removed int preference as its unreasonable and lowered the number of questions.


问:
Trying to identify IClass, Class, ClassImpl pattern
I've been seeing a lot of code recently that looks like this:

```<code>public interface IFoo { int Bar(); }

public static class Foo
{
    public static IFoo Create() { return new FooImpl(); }
    private class FooImpl : IFoo
    {
        public int Bar () { ... }
    }
}
</code>```

Basically, there is a contract defined by an interface, the the main business object class is a static class that provides factory methods, and there is an embedded class that provides the actual implementation.

There are some advantages to this pattern especially, the clean separation between the contract and the implementation.  Still, it seems a little ugly to me: especially the naming of a static factory class with a business object name rubs me the wrong way.

My questions are...

Is this an established pattern or style of development?

Are there any other advantages besides a rigorous hiding of implementation?

Is there a better way to achieve the same goals?

答:
I would regard the approach as being in many circumstances the best possible in a framework which does not allow interfaces to include public static helper methods.  I would consider IFoo.Create() preferable to Foo.Create() if such a thing were allowed, but unfortunately (at least in .NET languages) it isn't.

Despite the unfortunate naming of the factory method, I think such an approach is optimal in cases where:

There exists a single class which will be a reasonably good fit for the needs of code which won't need to use any features beyond those implemented by the interface.

Some clients may need things which can be used as implementations of the interface but which support other abilities as well, and the optimal internal design of an implementation which supports the added features may be totally different from the optimal design for an implementation which doesn't.

Methods which can be used with basic implementations of the interface should also be usable with the fancier implementations.

If a method takes a parameter of the "ordinary implementation class" type, such a method will not be useful with any of the fancier implementations.  Thus, unless there is some reason to have a method reject the fancier implementations, methods should generally use the interface type.  If a variable will never be passed to any methods except as an interface type, then the variable itself should probably be declared as that same interface type.

Although in situations involving a parameterless constructor/factory there may not be much advantage to using IWidget foo = Widget.Create() over IWidget foo = new Widget(), a factory method which accepts parameters can vary the type of the created object based upon the parameter values it is given.  This can be especially useful in cases involving immutable types.  For example, a method ImmutableSequence<T>.Create(IEnumerable<T> source); could copy source to an array and encapsulate that in an immutable wrapper in cases where no obviously-better alternative behavior suggests itself, but in cases where it recognizes the source type it might be able to do something better.  For example, if source instance implements an AsImmutableSnapshot() method, the Create method could chain to that and avoid having to create an extra layer of nesting.


答:
I think the other answers are being a bit too simplistic.

My approach would probable by to put it in configuration in code. I.e. keep the same data structure you were thinking for your configuration file, but don't put it in an external configuration file. Instead, build it in code.

In a python world, I'd do something like (I don't know c# well enough to know what it looks like there.):

```<code>VALIDATORS_BY_TYPE = {
   "Egg1": [Validator1(), Validator2(), Validator3()],
   "Egg2": [Validator2(), Validator4(), Validator5()]
}

def validate_egg(egg):
    for validator in VALIDATORS_BY_TYPE[egg.type]:
        validator.validate(egg)
</code>```

What do the alternatives look like? Let's suppose you wrote classes for each type of egg. You'd get something like:

```<code>class Egg(object):
   def __init__(self, egg):
       self.egg = egg

class Egg1(Egg):
   def validate(self):
       validator1.validate(self.egg)
       validator2.validate(self.egg)
       validator2.validate(self.egg)

class Egg2(Egg):
   def validate(self):
       validator2.validate(self.egg)
       validator4.validate(self.egg)
       validator5.validate(self.egg)

def MakeEgg(raw_egg):
    if raw_egg.type == 'Egg1':
         return Egg1(raw_egg)
    elif raw_egg.type == 'Egg2':
         return Egg2(raw_egg)
    else:
          raise "Unknown egg type!"

def validate_egg(raw_egg):
    MakeEgg(raw_egg).validate()
</code>```

That's considerably more code. Its also going to be much harder to change. Suppose that we decide that we'd actually like to accumulate the errors for each error type. If the first validator fails with the code above, we'd just bail. But instead, suppose that we want to add all the errors into a list and throw them together. With the configuration method, you just have to change validate_egg. If you wrote classes, you'll have to rewrite all of the Egg subclasses to add accumulation logic.

What about using an external configuration file? An external configuration file adds complexity. Here, I can construct my data structure directly, complete with references to validator objects. If I wanted to implement a configuration file I'd have to do something like:

```<code>validator_config = json.load(config_files.get_path("validator_config_file.json"))
VALIDATORS_BY_TYPE = {egg_type: [getattr(validators, name) for name in names]
                      for egg_type, names in validator_config}
</code>```

And this is going to break down and get more complex if you start needing to add parameters to validators, or other metadata.

On the other hand, configuration files do have the advantage of being easier to manipulate programmatically. Let's suppose that we want to give a description to the EggTypes, we'd need to rewrite our configuration block to be something like:

```<code>VALIDATORS_BY_TYPE = {
   "Egg1": EggType("Scrambled", [Validator1(), Validator2(), Validator3()),
   "Egg2": EggType("Sunny-side up", [Validator2(), Validator4(), Validator5()])
}
</code>```

That's going to be annoying rearrangement you'll have to do by hand. On the other hand, writing a throwaway script that parses a json configuration file, manipulates it to the new format and outputting a replacement is straightforward.

However, you do need to be careful in adopting a configuration based approach. It is often difficult to come up with a configuration that handles all the cases. When you can't handle a particular case through your configuration, the tendency is to add crazy hacks all over your code to handle it.

Title: Using reflection vs creating a new class

Body:
I and a friend are having an argument on what is the better technique to use in the following scenario:

An application we need to test has a number of components (lets call them Eggs); each component is a bag of predefined sub-components. These components are the input to our application, there is no way we can change/annotate these components at their source.

Now, we have a set of validators for each sub-component. It is not programatically possible to associate an Egg with its validators, so it has to be done manually for each new Egg (there are a finite number of eggs). Once the mapping is done, we can run each validator for each Egg to see if the Egg is good or rotten.

Now, my way of doing it is to have a config file which consists of the mapping between each Egg and its validators. Eg:

```<code>{
  Egg1: [validator1, validator2]
  Egg2: [validator5, validator7, validator2]
}
</code>```

Now we can read this file and use reflections to select the appropriate validator (from the list of all classes implementing IValidator) for each Egg.

My friend is averse to using reflections, and prefers to add a new C# class for each Egg everytime a new type of Egg is added. The class represents the Egg and runs the appropriate validators for that Egg.

Which way is better? I prefer the reflections method because everytime a new type of Egg shows up all we need to do is edit the config.

To clarify, an Egg is a selection from predefined list of sub-components. Assume that there will be no more sub-components, and hence there is no need for new validators. We cannot enumerate all possible Eggs because there are too many.

Body:
I think the other answers are being a bit too simplistic.

My approach would probable by to put it in configuration in code. I.e. keep the same data structure you were thinking for your configuration file, but don't put it in an external configuration file. Instead, build it in code.

In a python world, I'd do something like (I don't know c# well enough to know what it looks like there.):

VALIDATORS_BY_TYPE = {
   "Egg1": [Validator1(), Validator2(), Validator3()],
   "Egg2": [Validator2(), Validator4(), Validator5()]
}

def validate_egg(egg):
    for validator in VALIDATORS_BY_TYPE[egg.type]:
        validator.validate(egg)

What do the alternatives look like? Let's suppose you wrote classes for each type of egg. You'd get something like:

class Egg(object):
   def __init__(self, egg):
       self.egg = egg

class Egg1(Egg):
   def validate(self):
       validator1.validate(self.egg)
       validator2.validate(self.egg)
       validator2.validate(self.egg)

class Egg2(Egg):
   def validate(self):
       validator2.validate(self.egg)
       validator4.validate(self.egg)
       validator5.validate(self.egg)

def MakeEgg(raw_egg):
    if raw_egg.type == 'Egg1':
         return Egg1(raw_egg)
    elif raw_egg.type == 'Egg2':
         return Egg2(raw_egg)
    else:
          raise "Unknown egg type!"

def validate_egg(raw_egg):
    MakeEgg(raw_egg).validate()

That's considerably more code. Its also going to be much harder to change. Suppose that we decide that we'd actually like to accumulate the errors for each error type. If the first validator fails with the code above, we'd just bail. But instead, suppose that we want to add all the errors into a list and throw them together. With the configuration method, you just have to change validate_egg. If you wrote classes, you'll have to rewrite all of the Egg subclasses to add accumulation logic.

What about using an external configuration file? An external configuration file adds complexity. Here, I can construct my data structure directly, complete with references to validator objects. If I wanted to implement a configuration file I'd have to do something like:

validator_config = json.load(config_files.get_path("validator_config_file.json"))
VALIDATORS_BY_TYPE = {egg_type: [getattr(validators, name) for name in names]
                      for egg_type, names in validator_config}

And this is going to break down and get more complex if you start needing to add parameters to validators, or other metadata.

On the other hand, configuration files do have the advantage of being easier to manipulate programmatically. Let's suppose that we want to give a description to the EggTypes, we'd need to rewrite our configuration block to be something like:

VALIDATORS_BY_TYPE = {
   "Egg1": EggType("Scrambled", [Validator1(), Validator2(), Validator3()),
   "Egg2": EggType("Sunny-side up", [Validator2(), Validator4(), Validator5()])
}

That's going to be annoying rearrangement you'll have to do by hand. On the other hand, writing a throwaway script that parses a json configuration file, manipulates it to the new format and outputting a replacement is straightforward.

However, you do need to be careful in adopting a configuration based approach. It is often difficult to come up with a configuration that handles all the cases. When you can't handle a particular case through your configuration, the tendency is to add crazy hacks all over your code to handle it.


问:
Can JUnit be used to test this project?
I currently have an interesting situation occurring with my code, and after hacking away at what turned out to be a dead end for the last two weeks, I'm here asking those smarter than I to educate me on where I went wrong, and how I can perform my intended task correctly.

The setup:

We have a set of classes that perform various tasks but do so on one object that they pass around. Actions are performed to this object in each class before finally being processed and then sent back to the display layer for front end processing. This is a brief description of how the process works.

A collection of users is submitted via front end form
The collection of users is processed into an object with various parameters set within.
Multiple classes with various methods that process the object that was just created are executed one at a time. In each class, the object has various methods that perform tasks on certain actions, such as formulas, validation, etc.
the object is then sent to the front end for display of the processed object.

The task:

I'm attempting to build JUnit tests to help automate testing for this group of classes. This is how i have it configured

testConfiguration - instead of a form submission, I create a collection of users in various configurations based upon what we need to do for testing

testMain - This is the "root" class. It takes a configuration from the testConfiguration class needed for the current test run, creates it into an object with various parameters based upon the users passed, and then passed into the various classes for further processing

testClassesProcess - various classes that take the processed object from testMain, perform various actions on it (mainly mathematical type methods) and then return.

The issues:

Ran into a few really. The first is that you can't pass parameters to functions in JUnit tests, as it'll come up with initializeErrors. Also the @Autowired annotation in the classes being tested error out with NullPointerException, turns out that if enter the classes being tested from the JUnit suite, and they can't seem to resolve the variable that would be used with no issue when executed via the application normally.

WE currently use Java 1.7 with Hibernate, Spring, and JUnit to help give a visual of our stack.

So I'm wondering if after describing my situation if I'm trying to make JUnit put a round peg in square hole, if I'm just using JUnit wrong, or if there's a better solution that I could use to test this setup.

EDIT: My apologies if this seems vague. It's a workplace issue so I try not to give away anything proprietary, and to make it so others could relate.

答:
I understand you are leaving some details out due to the proprietary nature of the project. This answer is my take on what is going on based on how I understand the question. Please leave a comment if I am off base here and I will edit accordingly.

I think you may misunderstand how to use JUnit in complex projects.

Each test needs to stand on its own: there is no reason to pass parameters into tests, because each test should be treated conceptually as a main function. If you really need to do something before a test, you can annotate methods to run before/after each test or all tests (@Before, @After, @BeforeClass, @AfterClass). In practice, I have found such methods only useful for tests that connect to remote resources such as a database. While in general that is a bad idea, there are some specific cases where it makes sense. For example, when writing a driver where you really are testing the JDBC layer itself.

That brings me to the next point: in general, a unit test is for a specific piece of code, not the application as a whole or other components. To do this, you need to apply your SOLID principles to break software into smaller components that are loosely coupled to other components.

Once an object has one responsibility, you can more easily mock the components it relies on. Based on your breakdown of the various classes, you should consider using interfaces to define each component. That way you can have the "real" and mock classes both implement the interface and work correctly. This also has a benefit of helping ensure classes are only using the public interface (as opposed to package-private members) which further loosens coupling.

It sounds like you have a lot of interdependencies which make it difficult to "break off" a bite-sized chunk to test. I think you need to take a look at breaking up the design so you can inject your test mock objects which allow you to focus a single test on a single component which should not need additional information to run.

Title: Can JUnit be used to test this project?


答: No. An average task given to me isn't well defined until after I mess with it for a week, for which I need to pry the information out of whoever has it. Even then I feel hazy about what actually needed to happen.</p>

Title: For in-house programmers (non-project managers), do you normally receive project instructions written out in advance?

Body:
I'm fairly new to working as a programmer, at least working as a regular employee in-house for a company. I often become frustrated with my company's management style as they basically just pick out whatever random tasks catches the lead developer's fancy that day, or the day before, and give me the task (with tasks usually lasting less than 1 day). A lot of the tasks I have now are fairly small and are for adding enhancements to a web application, fixing bugs, etc.

I am bothered, however, by the fact that they don't plan ahead so as to give me an written outline of projects a few days in advance so that if, for example, I am rusty on something I can at least familiarize myself with it on my own time or at least have a more relaxed approach to the job so that everything doesn't have to be so reactionary on my part (where I can mull things during off-time over before starting work on them, etc)

I guess I'm just curious if this is the norm or if most development jobs value clearly laid out specifications for tasks and are able to prepare them somewhat in advance. I would be interested to hear anyone's experience / opinions, etc. Thanks


问:
Interfaces between multiple projects
I'm slightly confused over the following:

```<code>ProjectA
-------- GetUsers (Implements IDBConnector)
-------- IGetUsers
-------- UserModel

ProjectB
-------- Main
</code>```

I have two projects one main project (project B) and another which gets data from a database (project A). Project A has an interface which the main class makes use of. The GetUsers class is then injected within the main class of type IGetUsers.

This means there is a dependency of Project A for Project B as Project B needs to know how the interface is defined and the class definition itself. I am fine with this from a code standpoint but I can't help thinking that the interface should be kept somewhere else as it is essentially a contract and I am trying to follow the open/closed principle i.e. I shouldn't have to touch the main class to change how the database interaction is dealt with. In my example however if I remove Project A I lose the interface definition and I would have to modify the Main class.

I would have thought that Project B would be a good place to keep the interface but this would result in a circular reference as Project A would need to reference Project A for the interface declaration and vice versa for the class implementation.

The other option is to have a separate project for interfaces which I have seen mentioned in this question:

Sharing classes or interfaces between different projects

But to me this seems a little silly to have this example interface in a whole separate project while there is only one interface at current.

答:
You almost have you answer here:

I would have thought that Project B would be a good place to keep the interface but this would result in a circular reference ...

Following the Dependency Inversion Principle, interfaces should be defined by user, not the implementer. As you said in your question, the interface is essentially a contract; in order to invert the dependency, the user has to define the contract, so that the implementer depends on it. This contrasts with the normal flow of dependency, where the user depends on the contract that is forced on it by the implementation.

So, back to organizing the separate projects: If B is the user of the IGetUsers interface, then it must be the one to define it. If A provides an implementation of that interface, then it must depend on B. And now, not only to avoid circular references, but also to free B from any future dependencies that the may come, you can define a third project, C, which has the sole responsibility of composing the system out of the small modular pieces.

This concept is known as composition root, and is ideally the place where all dependency injection should live, leaving A and B outside the bounds of a dependency injection framework, if one were to use it.

Title: Interfaces between multiple projects

ContentLicense: CC BY-SA 4.0


问:
Using the optional 'self' reference in instance methods in Swift as a matter of style
Swift allows optional prefixing of method calls and property references to the current object instance via self. Removing these prefixes can declutter code but, depending on the length of the method and number of parameters and local variables, it can also make variable scope ambiguous.

Perhaps the answer is to refactor into smaller classes and methods, but sometimes that isn't always practical. Common examples are things like UIViewController subclasses and custom viewDidLoad() implementations or complex action handlers for UIGestureRecognizer subclasses. I've thought about this a bit since diving into developing an iOS app in Swift but am still on the fence. My ideal answer(s) would touch on:

If not referencing self has an practical downsides.

Whether mixing implicit and explicit references to self is worse that sticking to one or the other (I'm leaning towards yes).

Overall stylistic concerns with a focus on readability.

Instance variable naming styles versus local variable naming styles to mitigate ambiguity.

References to similar issues in other languages.

答:
I believe this is nothing but a matter of style - no "measure of readability" (which is always personal) can help you here.

So before I go any further, let me say this: Whatever the style choice, if you're working in a team, define a clear standard that the whole team must comply with, because if there is one thing that everyone can agree on that makes code less readable, is having to keep up with different style choices as you read it.

But now to the main subject: self, this or me, as present in many OO languages, are featured roughly for the following reasons:

Being able to pass an instance of the current object to others;

Accessing special properties that are otherwise unavailable, such as reflective property this.class in Java;

To allow otherwise conflicting names to be used in local scopes.

As with many other details that are abstracted away from us when we use OO languages (vtables, etc...), self could also be hidden, if it weren't for the reasons above.

So my opinion is that you should only use it when necessary, as above.
Of course, this idea only works well along with the practice of making small classes and methods; otherwise, both your local and global scopes are going to be so big that it will always be confusing, forcing the reader to jump up and down in the code, looking for the definitions. But I'm tempted to say, in these cases, that it is not the consistency of style that is going to save you.


问:
Using classes not designed for multiple sessions in servlet
I'm looking for a way to use a collection of Java classes in a servlet, which would provide some services to clients, but the classes were not designed with multiple sessions in mind, which seems to make that more difficult. To be specific, I want to load a language interpreter (ignoring security problems -- it will be accessible from localhost until I get security figured out), which has been written assuming there is just one user, so it has a lot of global state. Essentially I am looking for ways to ensure that each distinct client session has its own copy of the global state.

Is there a way to get the effect of sessions with an isolated copy of the global state by (let's say) working with the classloader? or some kind of container class? Maybe the servlet engine provides such a service? (I am working with Jetty, but I could switch to another servlet container if it provided such a service.)

Any light you can shed on this is much appreciated.

答: Containers don't give you this facility. Perhaps you can write some code to use a different classloader per user, but this is not a trivial task and IMMO you can do a better use of your time refactoring this code and removing the global state. Solve the problem instead of looking for difficult and complex workarounds.</p>


问:
Sending a notification to each participant 3 hours before the meeting starts
Let's assume an application that deals with meetings where some users will participate.

What is an efficient way to achieve this use case:

3 hours before the meeting should start, one reminder mail should be sent to each participant.

It's pretty easy to trigger a notification based on an Event, let's say a creation, or a cancellation of any meeting.
However, waiting for the "3 hours before" isn't an event..because each meeting has its own start date.

An easy way (and surely not performant) would be to have a background-process, that queries the storage (database for instance) in order to find events that matched the rule "within 3 hours before", and not flagged with some kind of processed.

What about a very high frequency of created meetings... this kind of process would be likely to be inefficient (without evoking the huge impact on the database) to ensure the exact precision of 3 hours (even with a marge of 5 minutes).

Any idea?

答:
I'm not sure that I see what "huge impact on the database" a process would have that polled the database every 5 minutes.

Presumably, you have some sort of table that stores your meetings and their start times.  It should be relatively easy to index the column that stores the start time and to write a query that looks for all the meetings set to start between 3 hours and 3 hours 5 minutes from now that would return a relatively small number of records relatively quickly.  Adding a column to this table to indicate whether the reminder had been sent or, even better, creating a table that mapped meetings to individuals and tracked whether individuals had been notified (people may be added to a meeting after the 3 hour window) would complicate the logic a bit but the same principles would apply-- you should be able to index the data in a way that would allow you to get the subset of data you need relatively quickly.

If you are really exceptionally performance-conscious, your DBA (or back-end developer) likely has a ton of options for tuning these sorts of queries.  Those will likely depend on the specific technology chosen (indexed views in SQL Server, materialized views in Oracle, etc.).


问:
Node.js on Apache server (Shared Hosting)

I would like to run Node.js/Express as a backend server mainly for handling WebRTC features in my app.
 I was just discussing this with my hosting provider and they rejected this request saying that Node.js is heavy and requires Java thus making it impossible to run on Apache so I need to upgrade my account to VPS.

Google tells me the opposite and many people are running Node.js on Apache.

 Is the above true or are they trying to take advantage of me?

答:
Actually you can run node.js on a typical shared hosting with Linux, Apache and PHP. Even NPM, Express and Grunt work fine. Here are the necessary steps:

1) Create a new PHP file on the server with the following contents and run it:

<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');
```

<p>2) Install your node app, e.g. jt-js-sample, using npm:</p>

<pre class="lang-php prettyprint-override"><code><?php
exec('node/bin/npm install jt-js-sample');
</code>```

3) Run the node app from PHP:

<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=81 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:81/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
    //If couldn't connect, try increasing usleep
    echo 'Error: ' . curl_error($curl);
} else {
    //Split response headers and body
    list($head, $body) = explode("\r\n\r\n", $resp, 2);
    $headarr = explode("\n", $head);
    //Print headers
    foreach($headarr as $headval) {
        header($headval);
    }
    //Print body
    echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);
```

Voila! Have a look at the working demo of a node app on PHP shared hosting.

EDIT: Here is my new project Node.php on GitHub.

Body:
Actually you can run node.js on a typical shared hosting with Linux, Apache and PHP. Even NPM, Express and Grunt work fine. Here are the necessary steps:

1) Create a new PHP file on the server with the following contents and run it:

<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');

2) Install your node app, e.g. jt-js-sample, using npm:

<?php
exec('node/bin/npm install jt-js-sample');

3) Run the node app from PHP:

<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=81 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:81/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
    //If couldn't connect, try increasing usleep
    echo 'Error: ' . curl_error($curl);
} else {
    //Split response headers and body
    list($head, $body) = explode("\r\n\r\n", $resp, 2);
    $headarr = explode("\n", $head);
    //Print headers
    foreach($headarr as $headval) {
        header($headval);
    }
    //Print body
    echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);

Voila! Have a look at the working demo of a node app on PHP shared hosting.

EDIT: Here is my new project Node.php on GitHub.


问:
Caching build results
This is a "technology/concept identification" question.

I have a rather large project in a DCVS repository.

Build times are loooong (about an hour) from a full clean.

The project is already divided into subprojects, with incremental building. But it still takes a very a long time when switching branches, etc., since I'll often have to compile a lot.

I had an idea of caching the subproject outputs (I'm using Scala, so in this case, it's a bunch of .class files), and publishing them with the hash of the source as the key. Before a build, I would download any outputs that matches the hashes of any of the subprojects. The "pain" of building would be shared and reused across the organization, including the CI server.

I can't have been the first person to think about this.

Is there a name for this caching-by-source (rather than explicit version)? Is it commonly implemented? Any existing tools around this?

EDIT: I have found one example in scons, a tool used primarily for C/C++ builds.

答:
sbt

The standard build tool for scala is sbt (Scala Build Tool).  Within sbt there are three ways to do dependencies:

Declarations in your project

Maven POM files

Ivy configuration

To use Maven, one would need to specify the resolvers for the location of your repository:

```<code>resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository"
resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"
</code>```

You could also override this by creating a local configuration file: ~/.sbt/repositories

```<code>[repositories]
local
my-maven-repo: https://example.org/repo
my-ivy-repo: https://example.org/ivy-repo/, [organization]/[module]/[revision]/[type]s/[artifact](-[classifier]).[ext]
</code>```

If you really had to, you could also specify a url and set up some way to host it locally on a server you control.  Note that this isn't an ideal solution

```<code>libraryDependencies += "slinky" % "slinky" % "2.1" from "https://slinky2.googlecode.com/svn/artifacts/2.1/slinky.jar"
</code>```

However, this is only half of the battle.  Sure you can pull the jars from some place, but you also need to put them there.  If you are not putting the modules out there for someone else to download and use, they are going to have to recompile them.

You could set up a Sonotype nexus server and then publish to it:

```<code>publishTo := Some("Sonatype Snapshots Nexus" at "https://oss.sonatype.org/content/repositories/snapshots")
</code>```

Or you could have a commonly mounted repository (I don't think this would be a best solution):

```<code>publishTo := Some(Resolver.file("file",  new File( "path/to/my/maven-repo/releases" )) )
</code>```

You can configure it to publish some things here and some things there:

```<code>publishTo := {
  val nexus = "https://oss.sonatype.org/"
  if (isSnapshot.value)
    Some("snapshots" at nexus + "content/repositories/snapshots")
  else
    Some("releases"  at nexus + "service/local/staging/deploy/maven2")
}
</code>```

But the thing there is that you need to publish it in order for other people to download it.

maven

Maven is (or should be) well known to Java developers.  It isn't something that is commonly used with scala.  But, it is possible to get scala and maven to work together.  Along with src/main/java you will have src/main/scala.  You will also have a plugin in your .pom:

<plugin>
  <groupId>net.alchim31.maven</groupId>
  <artifactId>scala-maven-plugin</artifactId>
  <version>3.1.3</version>
  <executions>
    <execution>
      <goals>
        <goal>compile</goal>
        <goal>testCompile</goal>
      </goals>
    </execution>
  </executions>
</plugin>
```

<p>At this point, you are using maven and you are deploying maven artifacts to the Sonotype nexus server.</p>

<h2>general things</h2>

<p>All of this, with either approach depends on something else though.  You need to have your project modularized so that small jars can be built, compiled, and deployed to the artifact server.</p>

<p>If your project is not configured this way, you will need to change it so that small independent parts are distinct.</p>

<p>You may find that the easiest thing to do (so you don't have to remember to do a publish or deploy) is to set up a continuous integration server that is fetching changes from your version control server, building them, and automatically deploying successful builds to the server.</p>

<p>This also implies some degree of discipline with versioning of the artifacts.  You may wish to look at semantic versioning.  The identifier for the release info so that you don't step on each other's toes and deploy competing snapshots or overwrite someone else's version number.  You will find yourself with versions like <code>1.0.3-pauld.0.1</code> so that they are namespaced.</p>

<p>And thus, you will specify with sbt or maven that this project uses some artifact at some version.  That pre-release version number will likely have the branch or author name in it.  It will be deployed to a server where you can then pull it.  When someone else switches to that branch those modules will be available for the build tool to download and use without having to recompile them.</p>

<h2>languages and tools</h2>

<p>A key thing to remember here is that one doesn't deploy .class files.  Instead, you are deploying .jars.  Everything is built around either locally compiled .class or downloaded libraries.  While one could conceive of doing this with other languages, with Java and Scala the IDEs would get <em>very</em> annoyed if the .class files and the .java or .scala files became out of sync.  If you're using <code>vim</code> and <code>javac</code> or <code>scalac</code>, then you might find other tools that pull singly compiled assets useful.</p>

<p>However, I'm going to point out that this isn't as trivial as it would first appear.  You will find things like <code>Outer$Inner.class</code> and <code>Outer$1$3.class</code> in instances where you've got inner classes (the second example is the compiled file for the third anonymous inner class in the first anonymous inner class in the class Outer).  With anonymous inner classes, this is position dependent in the file - add some code and <code>Outer$1.class</code> becomes <code>Outer$2.class</code>. This makes caching by source rather problematic and may not work at all with many JVM derived languages.  To give an example:</p>

```object App {

    def isEven(i: Int) = i % 2 == 0

    def isOdd(i: Int) = i % 2 == 1

    def main(args: Array[String]): Unit = {
        val n = (1 to 10).toList
        n.filter(isEven).flatMap(i => n.filter(isOdd).map(j => i * j))
    }

}
```

<p>when compiled with <code>scalac App.scala</code> you get:</p>

```App$$anonfun$main$1.class
App$$anonfun$main$2$$anonfun$apply$1.class
App$$anonfun$main$2$$anonfun$apply$2.class
App$$anonfun$main$2.class
App$.class
App.class
```

And you can see the issue of the order of the class things in the code can easily change.  This would make tools like scons much less useful and possibly even problematic.

Title: Caching build results

Body:
sbt

The standard build tool for scala is sbt (Scala Build Tool).  Within sbt there are three ways to do dependencies:

Declarations in your project

Maven POM files

Ivy configuration

To use Maven, one would need to specify the resolvers for the location of your repository:

resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository"
resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

You could also override this by creating a local configuration file: ~/.sbt/repositories

[repositories]
local
my-maven-repo: https://example.org/repo
my-ivy-repo: https://example.org/ivy-repo/, [organization]/[module]/[revision]/[type]s/[artifact](-[classifier]).[ext]

If you really had to, you could also specify a url and set up some way to host it locally on a server you control.  Note that this isn't an ideal solution

libraryDependencies += "slinky" % "slinky" % "2.1" from "https://slinky2.googlecode.com/svn/artifacts/2.1/slinky.jar"

However, this is only half of the battle.  Sure you can pull the jars from some place, but you also need to put them there.  If you are not putting the modules out there for someone else to download and use, they are going to have to recompile them.

You could set up a Sonotype nexus server and then publish to it:

publishTo := Some("Sonatype Snapshots Nexus" at "https://oss.sonatype.org/content/repositories/snapshots")

Or you could have a commonly mounted repository (I don't think this would be a best solution):

publishTo := Some(Resolver.file("file",  new File( "path/to/my/maven-repo/releases" )) )

You can configure it to publish some things here and some things there:

publishTo := {
  val nexus = "https://oss.sonatype.org/"
  if (isSnapshot.value)
    Some("snapshots" at nexus + "content/repositories/snapshots")
  else
    Some("releases"  at nexus + "service/local/staging/deploy/maven2")
}

But the thing there is that you need to publish it in order for other people to download it.

maven

Maven is (or should be) well known to Java developers.  It isn't something that is commonly used with scala.  But, it is possible to get scala and maven to work together.  Along with src/main/java you will have src/main/scala.  You will also have a plugin in your .pom:

<plugin>
  <groupId>net.alchim31.maven</groupId>
  <artifactId>scala-maven-plugin</artifactId>
  <version>3.1.3</version>
  <executions>
    <execution>
      <goals>
        <goal>compile</goal>
        <goal>testCompile</goal>
      </goals>
    </execution>
  </executions>
</plugin>

At this point, you are using maven and you are deploying maven artifacts to the Sonotype nexus server.

general things

All of this, with either approach depends on something else though.  You need to have your project modularized so that small jars can be built, compiled, and deployed to the artifact server.

If your project is not configured this way, you will need to change it so that small independent parts are distinct.

You may find that the easiest thing to do (so you don't have to remember to do a publish or deploy) is to set up a continuous integration server that is fetching changes from your version control server, building them, and automatically deploying successful builds to the server.

This also implies some degree of discipline with versioning of the artifacts.  You may wish to look at semantic versioning.  The identifier for the release info so that you don't step on each other's toes and deploy competing snapshots or overwrite someone else's version number.  You will find yourself with versions like 1.0.3-pauld.0.1 so that they are namespaced.

And thus, you will specify with sbt or maven that this project uses some artifact at some version.  That pre-release version number will likely have the branch or author name in it.  It will be deployed to a server where you can then pull it.  When someone else switches to that branch those modules will be available for the build tool to download and use without having to recompile them.

languages and tools

A key thing to remember here is that one doesn't deploy .class files.  Instead, you are deploying .jars.  Everything is built around either locally compiled .class or downloaded libraries.  While one could conceive of doing this with other languages, with Java and Scala the IDEs would get very annoyed if the .class files and the .java or .scala files became out of sync.  If you're using vim and javac or scalac, then you might find other tools that pull singly compiled assets useful.

However, I'm going to point out that this isn't as trivial as it would first appear.  You will find things like Outer$Inner.class and Outer$1$3.class in instances where you've got inner classes (the second example is the compiled file for the third anonymous inner class in the first anonymous inner class in the class Outer).  With anonymous inner classes, this is position dependent in the file - add some code and Outer$1.class becomes Outer$2.class. This makes caching by source rather problematic and may not work at all with many JVM derived languages.  To give an example:

object App {

    def isEven(i: Int) = i % 2 == 0

    def isOdd(i: Int) = i % 2 == 1

    def main(args: Array[String]): Unit = {
        val n = (1 to 10).toList
        n.filter(isEven).flatMap(i => n.filter(isOdd).map(j => i * j))
    }

}

when compiled with scalac App.scala you get:

App$$anonfun$main$1.class
App$$anonfun$main$2$$anonfun$apply$1.class
App$$anonfun$main$2$$anonfun$apply$2.class
App$$anonfun$main$2.class
App$.class
App.class

And you can see the issue of the order of the class things in the code can easily change.  This would make tools like scons much less useful and possibly even problematic.


问:
Design Patterns for Coordinating Change Event Listeners
I've been working with the Observer pattern in JavaScript using various popular libraries for a number of years (YUI & jQuery). It's often that I need to observe a set of property value changes (e.g. respond only when 2 or more specific values change). Is there a elegant way to 'subscribe' the handler so that it is only called one time? Is there something I'm missing or doing wrong in my design?</p>

答:
One technique (using Event-Based Systems with a Mediator):

I take advantage of the Mediator Pattern quite a bit -- one way to control event-flow is to instantiate different Mediator objects per-module, and pass only a specific Mediator to each module (as a, or in a sandbox) -- this will allow each module to only communicate through that specific medium, only when you say it should -- and, with this method, when you broadcast messages, you won't be broadcasting on the entire system / medium that the ApplicationDirector is listening on. An oversimplified implementation might look something like this:

```<code>// ApplicationCore / Mediator
var mediator = new Mediator();

var media = {
    authentication: mediator.installTo({}),
    ui: mediator.installTo({}),
    clients: mediator.installTo({})
};

// ... pass each medium to the given module

function broadcast(event, data) {
    for (var medium in media) {
        media[medium].fire(event, data);
    }
}

broadcast('command://start', null);

media.ui.on('action://form/sumbit', function (data) {
    media.authentication.fire('action://form/sumbit', data.email);
    media.clients.fire('action://form/sumbit', data.name.first, data.name.last);
});

// UI Module
sandbox.mediator.on('command://start', function () {
    // ...
    sandbox.mediator.fire('action://form/sumbit', formData);
    // ...
});

// Authentication Module
sandbox.mediator.on('command://start', function () {
    // ...
    sandbox.mediator.on('action://form/sumbit', function () { /* authenticate */ });
    // ...
});

// Clients Module
sandbox.mediator.on('command://start', function () {
    // ...
    sandbox.mediator.on('action://form/sumbit', function () { /* add new client */ });
    // ...
});
</code>```

Now, you can use a Mediator to handle when exactly certain changes (e.g. quantity) have an effect on the rest of the system. You even have more control over when a given module should notify the system of the change(s). Furthermore, if you're developing a very large-scale application -- using a Mediator that implements an EventHub is a good approach.

There are plenty of odd things about this example, but I hope you find this useful for what it demonstrates.

Body:
One technique (using Event-Based Systems with a Mediator):

I take advantage of the Mediator Pattern quite a bit -- one way to control event-flow is to instantiate different Mediator objects per-module, and pass only a specific Mediator to each module (as a, or in a sandbox) -- this will allow each module to only communicate through that specific medium, only when you say it should -- and, with this method, when you broadcast messages, you won't be broadcasting on the entire system / medium that the ApplicationDirector is listening on. An oversimplified implementation might look something like this:

// ApplicationCore / Mediator
var mediator = new Mediator();

var media = {
    authentication: mediator.installTo({}),
    ui: mediator.installTo({}),
    clients: mediator.installTo({})
};

// ... pass each medium to the given module

function broadcast(event, data) {
    for (var medium in media) {
        media[medium].fire(event, data);
    }
}

broadcast('command://start', null);

media.ui.on('action://form/sumbit', function (data) {
    media.authentication.fire('action://form/sumbit', data.email);
    media.clients.fire('action://form/sumbit', data.name.first, data.name.last);
});

// UI Module
sandbox.mediator.on('command://start', function () {
    // ...
    sandbox.mediator.fire('action://form/sumbit', formData);
    // ...
});

// Authentication Module
sandbox.mediator.on('command://start', function () {
    // ...
    sandbox.mediator.on('action://form/sumbit', function () { /* authenticate */ });
    // ...
});

// Clients Module
sandbox.mediator.on('command://start', function () {
    // ...
    sandbox.mediator.on('action://form/sumbit', function () { /* add new client */ });
    // ...
});

Now, you can use a Mediator to handle when exactly certain changes (e.g. quantity) have an effect on the rest of the system. You even have more control over when a given module should notify the system of the change(s). Furthermore, if you're developing a very large-scale application -- using a Mediator that implements an EventHub is a good approach.

There are plenty of odd things about this example, but I hope you find this useful for what it demonstrates.


问:
Easy way to make old javascript files conform to new quoting standard?
We've just started putting linting in place at my workplace, and a lot of the devs didn't realize our standards called for double-quotes everywhere. About 50% of the codebase uses single-quotes, so it's no easier to change the rule than to make the older code conform. Is there a tool or utility we could use to automatically fix older files? It's fine if we have to verify the output after, it's a lot easier to find problems in a few edge cases than to open and adjust every single file in a large codebase.

Before:

```<code>var foo = 'bar'
var bat = 'baz: "stuff"'
</code>```

After:

```<code>var foo = "bar"
var bat = 'baz: "stuff"' //allowed
</code>```

I'm open to any method, including using an existing tool, using regex in some kind of perl or batch file, anything to avoid spending large amounts of human time fixing what is ultimately a minor problem writ large across multiple code bases. The sheer magnitude of the problem dissuades people from attempting to fix it, and I'd like a way to help with that. Please leave discussion about the wisdom of this option out of it, as this is just one of many options I'm looking into -- if there's a nice easy way to deal with it, then the team leads will want to know about it, and if there's not, that will factor into the discussion as well.

Also keep in mind that this is just the rule that's most obvious now that the linting standards are in effect. Anything that can fix other errors as well (double equals where triple was needed also comes to mind) would be useful as well.

答:
Given your example, specifically the part where single quotes are not replaced, I don't think any off-the-shelf solution will do the job for you. I imagine that writing a custom tool which uses a JavaScript tokenizer would be too complicated as well.

On the other hand, you may replace automatically single quotes by double quotes. With regular expressions, you may go far enough to handle cases where single quoted string contains double quotes. Of course, there may be cases [practically] impossible to handle with regular expressions, such as:

```<code>var a = "'Hello \\\"World's.'"
</code>```

The problem which remains is to avoid regressions while replacing the characters.

If you have unit tests with enough coverage, you're probably fine. Just run those tests very frequently during the procedure to pinpoint the location of a mistake, if any.

If not, one of the ways to find regressions is to use Closure Compiler. It will generate consistent results independently of the quotes you use (all single quotes are replaced by double quotes). During the replacement of single quotes by double quotes, run Closure Compiler regularly and verify that its output is exactly the same as the one you had at the beginning.

Body:
Given your example, specifically the part where single quotes are not replaced, I don't think any off-the-shelf solution will do the job for you. I imagine that writing a custom tool which uses a JavaScript tokenizer would be too complicated as well.

On the other hand, you may replace automatically single quotes by double quotes. With regular expressions, you may go far enough to handle cases where single quoted string contains double quotes. Of course, there may be cases [practically] impossible to handle with regular expressions, such as:

var a = "'Hello \\\"World's.'"

The problem which remains is to avoid regressions while replacing the characters.

If you have unit tests with enough coverage, you're probably fine. Just run those tests very frequently during the procedure to pinpoint the location of a mistake, if any.

If not, one of the ways to find regressions is to use Closure Compiler. It will generate consistent results independently of the quotes you use (all single quotes are replaced by double quotes). During the replacement of single quotes by double quotes, run Closure Compiler regularly and verify that its output is exactly the same as the one you had at the beginning.


答:
As @MainMa has well pointed out, the technical problem might can be solved with a certain effort, but not easily without the risk of introducing some hidden bugs into your codebase (and the risk is high if the codebase is large, and you would probably not have asked such a question for a small codebase).

See this in contrast with the fact that this coding standard rule seems to serve only  some formal criteria, but it does not really improve readability. In such a situation I think you should actually discuss this with your team and ask if the rule is really so important, since

with or without the rule, everyone of your team must know that string literals in javascript can be created either with single or double quotes (your own example shows this clearly)

you have a lot of hassle for no benefit with your existing code

whenever you copy/paste some code from somewhere else, you will encounter the same hassle

I suggest you ask your team to remove that rule from your standard - coding standards should serve you, not vice versa. Maybe they leave it in as a recommendation for new written code, but not mandatory.

Title: Easy way to make old javascript files conform to new quoting standard?

Body:
We've just started putting linting in place at my workplace, and a lot of the devs didn't realize our standards called for double-quotes everywhere. About 50% of the codebase uses single-quotes, so it's no easier to change the rule than to make the older code conform. Is there a tool or utility we could use to automatically fix older files? It's fine if we have to verify the output after, it's a lot easier to find problems in a few edge cases than to open and adjust every single file in a large codebase.

Before:

```<code>var foo = 'bar'
var bat = 'baz: "stuff"'
</code>```

After:

```<code>var foo = "bar"
var bat = 'baz: "stuff"' //allowed
</code>```

I'm open to any method, including using an existing tool, using regex in some kind of perl or batch file, anything to avoid spending large amounts of human time fixing what is ultimately a minor problem writ large across multiple code bases. The sheer magnitude of the problem dissuades people from attempting to fix it, and I'd like a way to help with that. Please leave discussion about the wisdom of this option out of it, as this is just one of many options I'm looking into -- if there's a nice easy way to deal with it, then the team leads will want to know about it, and if there's not, that will factor into the discussion as well.

Also keep in mind that this is just the rule that's most obvious now that the linting standards are in effect. Anything that can fix other errors as well (double equals where triple was needed also comes to mind) would be useful as well.


问:
Introducing function waypoints to protect device
Defining a magic pointer or counter inside a program / class and checking for a fixed value before executing critical commands is a way to generate a barrier against wrong execution.

This check is supposed to be used on an embedded system which runs a program written in C/C++. Imagine a situation where the program counter is set to a dangerous address by mistake (EMI, bad programmer, hacker, Santa...). This piece of code would for example erase a flash cell in the MCU. We do not want that -> Put an if in front of every erase command and check for 0xDEADBEEF.

I know the gain is not too high and the program looses flexibility. I also thought about having waypoints (Erase -> Is write set? -> Do you have firmware data?)

What is this technique called? Are there any papers about it or even patterns?

答:
A field you add to a structure for the purpose of error checking is often called a dog tag (I think it's so called after Code Complete - Steve McConnel).

A dog tag is used to check for corrupted memory:

when you allocate a variable put a value that should remain unchanged into its tag file;

when you use the structure check the tag's field value (if the tag field doesn't have the expected value the data has been corrupted);

when you delete a pointer corrupt the tag so that if you accidentally try to free the same pointer again you'll detect the corruption.

Canary values on the stack are dog tag fields (take a look at Is “dog-tag” fields used in some software?).


答:
All exceptions are not bugs. It can be a topic of debate that all bugs are exceptions or not.

We can say exceptions are the events that are not part of the normal or expected flow of application. These events can be independent of how the code is written where as a bug is essentially result of bad code(like wrong calculation).

Here is an example of how not handling an exception can be a bug.

Let us suppose there is a program that writes some data to an external storage device. While writing the external storage device was unplugged, crashed or may be destroyed(for what ever reason). Now this is an exceptional case, now regardless the programming language supports exceptional handling or not if the program crashes or misbehaves due to this event, it is a bug.(The end user may have not idea what happended. It is also very unpleasent). But if program aborts the process gracefully, notify the user(in other words handle the exeption) this is clearly not a bug.

The try catch machanism programing languages provide is essentially a tool to ease our way out to handle unexpected events.

Title: Why not use the word bug instead of exception?

Body:
If we refer to exceptions as bugs, why not just call it a bug in the first place instead of an exception?

If in the code it's called exception and as soon as it occurs it's called a bug. Then why not call it a bug in the first place?

Thank you for any answer or comment.


答: You might legitimately raise an exception yourself, you would hopefully never introduce a bug on purpose.</p>


答:
The most efficient way would be for the client application that is responsible for sending the email to query the DB at startup and remember the next meeting time. It would sleep until 3 hours before this time, then wake up and send the email.

However, the application would also have to be informed of changes to the meeting schedule - either meetings that are added or deleted, and update its next-wake time accordingly. Typically, reading the next-meeting time at each update. How you notify the application of changes is up to you - I would reuse the application as the entry point to the meetings data, so all meeting changes, additions or deletions are sent to the application for processing which then stores the updates in the DB (after all, something has to do this job, might as well be this app).

Title: Sending a notification to each participant 3 hours before the meeting starts

Body:
Let's assume an application that deals with meetings where some users will participate.

What is an efficient way to achieve this use case:

3 hours before the meeting should start, one reminder mail should be sent to each participant.

It's pretty easy to trigger a notification based on an Event, let's say a creation, or a cancellation of any meeting.
However, waiting for the "3 hours before" isn't an event..because each meeting has its own start date.

An easy way (and surely not performant) would be to have a background-process, that queries the storage (database for instance) in order to find events that matched the rule "within 3 hours before", and not flagged with some kind of processed.

What about a very high frequency of created meetings... this kind of process would be likely to be inefficient (without evoking the huge impact on the database) to ensure the exact precision of 3 hours (even with a marge of 5 minutes).

Any idea?


问:
Develop GUI and logic in a team the right way?
I am planning to start a small project with a friend. I will be developing the GUI using JavaFX in the MVC pattern and he will be responsible for the model/logic.

My question is: how can we achieve a save parallel developing, how do companies do that? Would we just write an interface for the model together, that specifies what functionality I will need in the controller and thus he has to implement?

Thx in advance.

答:
The best way is to develop the 2 aspects in different processes and use a form of IPC to communicate between the two. He will develop a "server" process that must define an API for you to use. (You don't have to use the client-server model like this so you could develop in 2 different linked modules, but it helps for testing and also helps to reuse the server components if you want to change the GUI to a web or mobile interface instead)

In any other form of doing what you want - ie 2 developers writing code in different, interlinking areas, the only sane way is to define the API regardless. Any other way will descend into a madness of chaotic developments where you continually break each others code.

Note that the API can continually evolve, often in response to your needs, but its usually a good idea to start with some form of design where you come up with a base from which to build on.