问:
Design Pattern for Removing Default Listeners
We have a standard GUI control with a bunch of default listeners like that:

```<code>class OurControl extends Control {

    OurControl() {
         addMouseWheelListener(new DefaultMouseWheelListener());
    }

}
</code>```

The defaults are good for the standard use-cases, but now the customer wants to use their own listeners in some cases. I'm searching for the most elegant way to achieve that.

Idea 1: (it just feels weird to me, and I don't like to maintain a list of listeners that might be removed)

```<code>class OurControl extends Control {

    MouseWheelListener defaultListener = new DefaultMouseWheelListener();

    OurControl() {
         addMouseWheelListener(defaultListener);
    }

    void removeDefaultMouseWheelListener() {
         removeMouseWheelListener(defaultListener);
    }
}
</code>```

Idea 2: (I like this one, even though technically speaking the listener stays where it is; it at least follows the standard bean pattern)

```<code>class OurControl extends Control {

    public boolean enableMouseWheel = true;

    OurControl() {
         addMouseWheelListener(new MouseWheelListener() {
             void mouseWheelMoved(final MouseWheelEvent e) {
                 if (enableMouseWheel)
                     doMagic();
             }
         });
    }
}
</code>```

What is a good way to achieve this goal?

答:
An alternative approach I've seen is listeners having the ability to cancel subsequent listeners. For example, DOM Events supports this.

This relies on listeners being called in a well-defined order. I think it's pretty standard that listeners are called in reverse order of registration, but check your particular framework.


答:
Option 2 is by far the best, if I correctly understand what you mean.

Your default mouse wheel listener presumably does a certain job; let's say, it scrolls.

Your client's need to set their own listener tells me that they don't want you to scroll, so that they can use the mouse wheel for something else.

But you see, how you achieve this scrolling on mouse wheel is none of their business, and the fact that you achieve it with a mouse wheel listener is just a little implementation detail that they need not and should not be concerned with.  So, instead, your control should offer a "Scroll on Mouse Wheel" option, controlling this aspect of its behavior, which your client may set to false if they don't like it.

Then, your client is also free to add their own mouse wheel listener to do their own stuff, like perhaps zoom instead of scroll.  If they forget to cancel the "Scroll on Mouse Wheel" option, they will get both behaviors, and that's perfectly understandable.

ContentLicense: CC BY-SA 3.0

Title: Design Pattern for Removing Default Listeners

Body:
We have a standard GUI control with a bunch of default listeners like that:

```<code>class OurControl extends Control {

    OurControl() {
         addMouseWheelListener(new DefaultMouseWheelListener());
    }

}
</code>```

The defaults are good for the standard use-cases, but now the customer wants to use their own listeners in some cases. I'm searching for the most elegant way to achieve that.

Idea 1: (it just feels weird to me, and I don't like to maintain a list of listeners that might be removed)

```<code>class OurControl extends Control {

    MouseWheelListener defaultListener = new DefaultMouseWheelListener();

    OurControl() {
         addMouseWheelListener(defaultListener);
    }

    void removeDefaultMouseWheelListener() {
         removeMouseWheelListener(defaultListener);
    }
}
</code>```

Idea 2: (I like this one, even though technically speaking the listener stays where it is; it at least follows the standard bean pattern)

```<code>class OurControl extends Control {

    public boolean enableMouseWheel = true;

    OurControl() {
         addMouseWheelListener(new MouseWheelListener() {
             void mouseWheelMoved(final MouseWheelEvent e) {
                 if (enableMouseWheel)
                     doMagic();
             }
         });
    }
}
</code>```

What is a good way to achieve this goal?


问:
cpp and h/hpp #include: "why" question
Why does the source include a header and not also the other way around? I googled it but only found questions regarding the use of header files, how to include them but nowhere to say why it is like it is.
If the header is merely the declaration, how does the compiler know the definition only from it?

For example: take foo.cpp, bar.h, bar.cpp. This is what everybody does:

in foo.cpp:

#include "bar.h"

but the bar.cpp is not included neither in the bar.h or foo.cpp. That's why I deem logical that bar.cpp be included in bar.h and so, indirectly in foo.cpp.

答:
If you're a compiler, then Life is easy so long as you know what everything "looks like".  For example, 'X' is a 64-bit integer, 'Y' is a pointer to something of that Type, 'Z' is an array of this Type and size, and so on.
Take this to the extreme and you get an early Pascal compiler, where the main method has to be the very last thing in the source file!  Everything else has to be defined first.  Writing code in this way is painful, because the order is natural to the compiler but not to the likes of you and me.

Enter the Header (.h) file.

It describes all the methods that that appear in your .cpp file so the compiler can "make a note" of what they look like (known as "forward declarations") and then just recognise them when they appear, again, further down in the code.  Otherwise, it just has to assume some "default" definition for any method and then complain like mad when it finds a different implmentation signature (some Solaris compilers assume "int methodName( int )" as a default, IIRC.

But, even with all this, you still don't need a Header file.

You can do all that within the .cpp file itself.

Now add "reusable code" into the mix.  Other .cpp files want to use the methods in your .cpp file but the compiler still needs to know what those methods "look like".

By splitting the method declarations out into a Header file, you're effectively "publishing" the API provided by your .cpp file.  (ADA has "package" and "package body", most of the Microsoft world just smooshes all the declaration and implementation details into a single file, the dll).

So the Header file gives you a single declaration of your methods, usable by both you and any number of others who might need to use those methods.  Note, however, that the people using your Header file don't need your .cpp file at all; [object] code compiled in this way always has "holes" in it (unresolved function pointers); it's the linker's job to join all the dots together.

Title: cpp and h/hpp #include: "why" question


问:
Would adding more digits be a way to scale a order generation service?
I am working on interview questions from Amazon.com Software Development Engineer Intern Interview Questions.

One of the interviewees was asked "give a scalable system design of Amazon.com's order number generation service."

I did some preliminary research Amazon Order Number and found that Amazon generates a 17 digit order number of the form 3-7-7, where the last 14 digits are seemingly pseudo-random with psuedo random meaning generated by an "algorithm that uses mathematical formulas to produce sequences of random numbers" Psuedo-Random Definition

I verified one on my own and saw that one of my order numbers - 112-9036246-9502632 followed this guideline.

How would you give a scalable, as in "ability of a computer application to continue to function as its size is changed to meet user end" Scability system design of this? To me this order number generation service is already pretty scalable cause that 3-7-7 combination should allow for a great range of combinations to accomodate for a great number of users. But if you wanted this service to be more scalable, would you just add more digits to the end to allow for more combinations of order numbers, that way you can accommodate for more orders?

答: The trick is in the first three digits.  The last 14 digits are guaranteed to be unique within a certain domain, (say, a server,) so the first 3 digits must uniquely identify each domain.  Therefore, every 17-digit number is guaranteed to be unique.</p>


问:
License for internal program
Pending approval, I will be using NPOI for internal programs at work.  I will be documenting the associated license, and I find myself wondering about licensing on the programs themselves.

In short:

Do I need a license for company internal programs?

If so, what 'stock' licenses are available?  I'm not having any luck finding any.

EDIT:

My employer does own the work.  I like the style proposed by https://softwareengineering.stackexchange.com/a/234526 suggesting a LICENSE-3RD-PARTY.txt , which made me question if I should have a license on the program itself.  I suppose a disclaimer may be more appropriate.  We are an international company, so that may come into play.  Previous programs haven't included any disclaimers, etc.  I will ask my boss if we need to pursue any formal license/disclaimer.

答:
Consider that the company likely owns the copyright (work for hire) on the programs being created, and is also the user.

This means that the license is irrelevant: a license is an agreement the owner of the software's copyright and anyone who wishes to use the software. If the two parties are the same entity, using any license makes no sense.

That being said, it would make sense to include a disclaimer stating that the software is owned and copyrighted by the company and individual users employed by the company andacting on its behalf should not redistribute or otherwise infringe on the company's copyright.

Please note that the scope of this answer is the licensing (or lack thereof) only and does not constitute legal advice. The final say rests with your employer's legal department.

Title: License for internal program


问:
Which part of the code should rewind a file pointer?
If you had a function that took a handler to a file and then performed some actions that moved the pointer, would you expect it to put the pointer back when it was finished? Additionally, would you generally expect it to rewind to the start before it began its work?

```<code>def hash_contents(fp):
    original_pos = fp.tell()
    fp.seek(0)
    # do hashing / whatever
    fp.seek(original_pos)
</code>```

I've looked around a little to see what the most common assumptions are but I'm not sure what a good rule to follow is. For example, shutil.copyfileobj copies from whatever position the file started in and then consumes to the end.

What are the pros / cons and are there any standard rules of thumb to follow when designing these sort of functions?

This is actually a subquestion of something I was asking over at StackOverflow (Prefer BytesIO or bytes for internal interface in Python?) that really seems more suitable over here.

答:
Looking at it from the perspective of other languages, in both Java and C++ many libraries and interfaces accept a generic InputStream/istream as a parameter when they need to read something (and then to read a file, you'd pass FileInputStream/ifstream).

Aside from the benefit of being able to read from other input sources than files, input streams are pretty much always considered to be one-way-only, which makes it immediately clear to the programmer that you shouldn't expect it to rewind the file pointer.


问:
Should changes to FNV-1A's input exhibit the avalanche effect?
This is kind of related to Which hashing algorithm is best for uniqueness and speed?. In that question, the excellently written top answer notes,

Randomnessification

The other subjective measure is how randomly distributed the hashes are. Mapping the resulting HashTables shows how evenly the data is distributed.

(here, "random" is not being used to mean "deterministic" — all of the functions under consideration are deterministic.)

Based on that question's excellent answer, I implemented FNV-1A. However, the results I'm getting do not seem particularly "random"ly distributed:

```<code>In [19]: for x in xrange(10):
   ....:     h = Fnv1A(); h.update(b'testing' + str(x)); print hex(h.value)
   ....:
0x3e249fc5d899c731L
0x3e249ec5d899c57eL
0x3e249dc5d899c3cbL
0x3e249cc5d899c218L
0x3e24a3c5d899cdfdL
0x3e24a2c5d899cc4aL
0x3e24a1c5d899ca97L
0x3e24a0c5d899c8e4L
0x3e2497c5d899b999L
0x3e2496c5d899b7e6L
</code>```

Notice that the vast majority of the bits in the output here are the same.

Is FNV-1A supposed to be an extremely discontinuous function? i.e., the output changes drastically for small changes in the input; it exhibits the Avalanche effect.

Note that this is orthogonal to being uniformly distributed, which I also want.

I'm attempting to use FNV-1A to simply randomly distribute users into one of n weighted buckets. None of the inputs are user-controlled, so security is not of much concern, but the inputs are highly not random (they're auto-incrementing integers…); I do, however, need the output two be random (but deterministic): for a given user ID, it should be random which bucket they end up in.

I actually asked another similar question a while ago; I understand that hash outputs don't necessarily need to be random (for hashtables, all you really care about is that they don't collide). For my particular application, I unfortunately need randomness.

(In case you're curious about the correctness of my implementation,

```<code>In [22]: h = experiment.Fnv1A(); h.update(b'foobar'); h.value
Out[22]: 9625390261332436968L
</code>```

…as this is for work, I'm trying to share as little code as needed. This question is more about FNV-1A itself, rather than my particular implementation.)

答:
From your requirements it rather sounds like you should be using a secure (cryptographic) hash.

To your actual question:

Is FNV-1A supposed to be an extremely discontinuous function? i.e., the output changes drastically for small changes in the input; it exhibits the Avalanche effect.

we can quickly get an answer of No by looking at the FNV test vectors linked from the FNV homepage. Your foobar => 0x85944171f73967e8 test case is here, and also here we find these test cases:

```<code>input    output
"a"      0xaf63dc4c8601ec8c
"b"      0xaf63df4c8601f1a5
"c"      0xaf63de4c8601eff2
"d"      0xaf63d94c8601e773
"e"      0xaf63d84c8601e5c0
"f"      0xaf63db4c8601ead9
</code>```

It's clear that this hash is not one to use if you want small changes to avalanche.

Body:
From your requirements it rather sounds like you should be using a secure (cryptographic) hash.

To your actual question:

Is FNV-1A supposed to be an extremely discontinuous function? i.e., the output changes drastically for small changes in the input; it exhibits the Avalanche effect.

we can quickly get an answer of No by looking at the FNV test vectors linked from the FNV homepage. Your foobar => 0x85944171f73967e8 test case is here, and also here we find these test cases:

input    output
"a"      0xaf63dc4c8601ec8c
"b"      0xaf63df4c8601f1a5
"c"      0xaf63de4c8601eff2
"d"      0xaf63d94c8601e773
"e"      0xaf63d84c8601e5c0
"f"      0xaf63db4c8601ead9

It's clear that this hash is not one to use if you want small changes to avalanche.


问:
Web API: avoiding name conflicts in URL query parameters
I am implementing a REST-like API and have just faced an interesting problem. There is a need to provide a resource with an open list of query parameters to filter the results.
For example:

```<code>GET /api/items?field1=value1&field2=value2
</code>```

Field names are configurable, so I don't have the complete list of possible names.

There are also parameters with special meaning, e.g. orderBy=field5

The problem is when there is a field with the same name as one of the pre-defined parameters. The API has to somehow distinguish between them.

Many command-line programs use two hyphens ("--") to mark the end of options and start of arguments. I think of something analogous in URLs.

Is there any good practice in this subject?

答:
An easy solution is to add a prefix to all the query fields (or at least the customized). In my case the fields can be in different classes, e.g. "core" or "custom" so it is convenient to use prefixes to differentiate them. For example, "core.field1", "custom.field10". As a side effect, it will resolve the problem with conflicts.
If someone adds a field called orderBy, it still will be able to be used for filtering without any conflict with the special parameter of the same name:</p>

```<code>custom.orderBy=something&orderBy=field1
</code>```

Body:
An easy solution is to add a prefix to all the query fields (or at least the customized). In my case the fields can be in different classes, e.g. "core" or "custom" so it is convenient to use prefixes to differentiate them. For example, "core.field1", "custom.field10". As a side effect, it will resolve the problem with conflicts.
If someone adds a field called orderBy, it still will be able to be used for filtering without any conflict with the special parameter of the same name:

custom.orderBy=something&orderBy=field1


问:
How to sell DRY architecture
I'm sure most are familiar with the phrase DRY in the software world - Don't Repeat Yourself.  This is a fundamental principle of good software development.

Here is a question (background first).

We are an high level educational institution (college), and are putting together a new MVC application.  The current version of this application is for faculty and staff who can perform various tasks such as searching for students, viewing grades and other academic information about that student.  There are features to help advisers to enter notes about their students.  Likewise, there are views to show overall college details and status for given graduation classes.  All of this has security built in maintaining FERPA compliance.

The next thing we are going to do is to implement a "student" version - something the students can log into to see much of the same information - only tailored for the student.  They would not be able to see other's information, but only their own.  But, they will be able to see the same college level detail information.

My proposal is to make this all one application and use permissions to manage the views and data that is being displayed to the user.  Others on the team think that it should be two completely separate applications because of the complexity of modifying the views based on the authorization level of the user.

Some of the problems I am seeing with making this a separate application are:

MANY of the views would actually be the same data being displayed.  Both the HTML and model code would have to be copied between the solutions - not to mention the unit tests.  I don't want to maintain the same code in both places which will eventually become very difficult to maintain.

The skins for both sites are the same - any changes would have to be done in both places.

The authentication and authorization parts are exactly the same for both applications.  We are authenticating against AD and have a common authorization database.

The main reason some others on the team want separate applications is because there is more complexity regarding having to decide who is making the calls and then making sure they get the views and data they are supposed to.

Now for the questions - Is there anyone who thinks I am wrong in my position on this?  If so, please explain why so I may understand that side of the equation better.  Likewise, if you agree with me, do you have a better way of explaining the given rational with better/more reasons than I've stated above?

Thanks for any suggestions/thoughts!

答:
Others on the team think that it should be two completely separate
  applications because of the complexity of modifying the views based on
  the authorization level of the user.

Really? they don't realise they have to create these views anyway if they made 2 separate applications? How hard is it to put both views into the same application and decide which to show based on a flag!

Now, admittedly that doesn't completely implement DRY but its a very good start - you get to reuse all of the back end code. This is where the majority of the work is going to be done and so this is where the majority of your effort is going to go. UI is almost an afterthought in comparison.

This should get you past the "2 applications" problem, and once they start creating the same view twice in the same project, then I think they'll start to consider the duplication and will start to think of the parts that can be combined in a single view... and then you can say "I told you so" with conviction and smugness :-)

Incidentally, the best applications are writing in a decoupled manner like this, the back-end provides an API that the client consumes. This should solve the 'complexity of calls' problem, as you will design the back-end to provide the required data and logic (hopefully) before you start coding. Imagine you're using data provided by a 3rd party service on the internet - you do not get to tell them what data to provide, instead you call their APIs and use what they give you.

Title: How to sell DRY architecture


问:
Selecting the (right?) technology and environment
We are two developers on the edge of starting new web product development.

We are both fans of lean start-up approach and would like to practice continuous deployment.

Here comes the dilemma - we are both coming from a C# / Windows background and we need to decide between:

Stick to .NET and Windows, we will not waste time on learning new technologies and put all our effort in the development.

Switch to Ruby on Rails and Linux which has a good reputation of fast ramp up and vast open source support. The negative side is that we will need to put a lot of effort in learning Ruby, Rails and Linux...

What would you do? What other considerations should we take?

答:
Just do it in c# and dot net.

You are good at already

its better than ruby on rails

ContentLicense: CC BY-SA 2.5


答:
The biggest reason against two applications is that you are very likely to have to implement user rights anyway. Presumably you aren't going to allow an advisor to enter notes about students he doesn't advise, or delete important information without uber-admin privilege, or edit information about advisors other than themselves? Once you have this mechanism in place, extending it to the students should be straightforward.

NB: If your superiors imagine that academic advisors are somehow above mere mortals in terms of not misusing privileges, they have a wake-up call coming.

Title: How to sell DRY architecture

Body:
I'm sure most are familiar with the phrase DRY in the software world - Don't Repeat Yourself.  This is a fundamental principle of good software development.

Here is a question (background first).

We are an high level educational institution (college), and are putting together a new MVC application.  The current version of this application is for faculty and staff who can perform various tasks such as searching for students, viewing grades and other academic information about that student.  There are features to help advisers to enter notes about their students.  Likewise, there are views to show overall college details and status for given graduation classes.  All of this has security built in maintaining FERPA compliance.

The next thing we are going to do is to implement a "student" version - something the students can log into to see much of the same information - only tailored for the student.  They would not be able to see other's information, but only their own.  But, they will be able to see the same college level detail information.

My proposal is to make this all one application and use permissions to manage the views and data that is being displayed to the user.  Others on the team think that it should be two completely separate applications because of the complexity of modifying the views based on the authorization level of the user.

Some of the problems I am seeing with making this a separate application are:

MANY of the views would actually be the same data being displayed.  Both the HTML and model code would have to be copied between the solutions - not to mention the unit tests.  I don't want to maintain the same code in both places which will eventually become very difficult to maintain.

The skins for both sites are the same - any changes would have to be done in both places.

The authentication and authorization parts are exactly the same for both applications.  We are authenticating against AD and have a common authorization database.

The main reason some others on the team want separate applications is because there is more complexity regarding having to decide who is making the calls and then making sure they get the views and data they are supposed to.

Now for the questions - Is there anyone who thinks I am wrong in my position on this?  If so, please explain why so I may understand that side of the equation better.  Likewise, if you agree with me, do you have a better way of explaining the given rational with better/more reasons than I've stated above?

Thanks for any suggestions/thoughts!


答:
Clearly those for 2-apps solution may lack experience. Just imagine 'adding this one more field' made twice.

Most MVC frameworks allow you to create separate routings for separate users (think of example.com/admin, example.com/student, example.com/professor).

This of course makes a separate views, but (important!) you can extract common parts (RoR calls them partials, cakePHP calls them elements). This is well estabilished approach

(you don't want to end up with if's in your views to determine if you should show this part or not).

Remember this will increase complexity - but not that much. In perspective there are years of managing this app. You'll pay more when maintaining two versions of almost the same apps.

// Edit: Also check julia-hayward response:
https://softwareengineering.stackexchange.com/users/43098/
this is excellent point - I would vote it up, but don't have enough points to do so.

Title: How to sell DRY architecture


答:
putting together a new MVC application

Some of the problems I am seeing with making this a separate
  application are:

```<code>MANY of the views would actually be the same data being displayed.
</code>```

An argument in favo(u)r of a single app.

Both the HTML and model code would have to be copied between the
  solutions - not to mention the unit tests. I don't want to maintain
  the same code in both places which will eventually become very
  difficult to maintain.
  Won't the model code be identical, which two views and one or  two controllers?

```<code>The skins for both sites are the same - any changes would have to be done in both places.
</code>```

CSS?  Or, you could use AngularJs with templating for your views.

```<code>The authentication and authorization parts are exactly the same for both applications.
</code>```

We are authenticating against AD and have a
  common authorization database.

Of course, if that code offers a clean API then it can be used whether you have one app or two.

Personally, I like AngulrJs for this as it so easily lets you show/hide parts of a web page based on a single datum in your controller's $scope.

```<code><div ng-hide="isStudent" class="ng-hide">
   staff specific HTML goes here ...
</div>
</code>```

and, in the controller, just set $scope.isStudent as appropriate.

So, my vote is for a single app and AngularJs

Title: How to sell DRY architecture

Body:
putting together a new MVC application

Some of the problems I am seeing with making this a separate
  application are:

MANY of the views would actually be the same data being displayed.

An argument in favo(u)r of a single app.

Both the HTML and model code would have to be copied between the
  solutions - not to mention the unit tests. I don't want to maintain
  the same code in both places which will eventually become very
  difficult to maintain.
  Won't the model code be identical, which two views and one or  two controllers?

The skins for both sites are the same - any changes would have to be done in both places.

CSS?  Or, you could use AngularJs with templating for your views.

The authentication and authorization parts are exactly the same for both applications.

We are authenticating against AD and have a
  common authorization database.

Of course, if that code offers a clean API then it can be used whether you have one app or two.

Personally, I like AngulrJs for this as it so easily lets you show/hide parts of a web page based on a single datum in your controller's $scope.

<div ng-hide="isStudent" class="ng-hide">
   staff specific HTML goes here ...
</div>

and, in the controller, just set $scope.isStudent as appropriate.

So, my vote is for a single app and AngularJs


问:
Is this a good service locator, and is this service locator pattern(?) OK?
I'm working in Zend framework 1 and was using Zend_Registry to store objects so that I could replace them in my controllers while unit testing:

```<code>$auth = Zend_Registry::get('Auth'); // set in Bootstrap.php
</code>```

I wanted to store closures that could be executed when they were required (rather than all during Booostrtap even if they weren't used in that request), but Registry doesn't seem to do this. I guess prior to 5.3 closures weren't around?

So, I built my own service locator class. I thought to extend Zend_Registry but prefer to have something that can be used outside ZF1, plus it's pretty basic anyway:

```<code><?php

class App_Services
{
    /**
    * @var array $container will store our services
    */
    private $container = array();

    /**
    * Returns the *Singleton* instance of this class.
    *
    * @staticvar Singleton $instance The *Singleton* instances of this class.
    *
    * @return Singleton The *Singleton* instance.
    */
    public static function getInstance()
    {
        static $instance = null;
        if (null === $instance) {
            $instance = new App_Services();
        }

        return $instance;
    }

    /**
    * Get a service from the container
    *
    * @param string $name Index of the service in container
    * @return various Service
    */
    public function get($id)
    {
        $instance = self::getInstance();

        // if not set, return null
        if (! isset($instance->container[$id]))
            return null;

        // if a closure, call it and return the return value
        if ($instance->container[$id] instanceof \Closure) {
            $instance->container[$id] = $instance->container[$id]();
            return $instance->container[$id];
        }

        return $instance->container[$id];
    }

    /**
    * Set a service in the container
    *
    * @param string $id Name (index) of the service in container
    * @param string $service Service to store
    */
    public function set($id, $service)
    {
        $instance = self::getInstance();

        $instance->container[$id] = $service;
    }
}
</code>```

.. and on Bootstrap I can do:

```<code>$auth = App_Services::set('Auth', function() {
    return new Auth();
});
</code>```

.. then within my controller actions I can do:

```<code>$auth = App_Service::get('Auth');
</code>```

.. as before.

Anyway, is this a good implementation of a service locator? Also could either this or Zend_Registry used in this way, be regarded as a service locator? I'd like to understand the pattern better as I read service locator pattern is a good idea, then I read it's an anti pattern, but I think some times it depends on how patterns are implemtemted whch makes then good patterns or anti patterns. I'd appreciate any advice on this, thanks.

答:
I would change few things:

remove singleton, make private static $container = [] anyway you're just using static methods to retrieve it.

consider throwing special exception when getting not set service.

re-consider automatic caching for services (it is possible you may not want it for every service)

Considering pattern/anti pattern discussion I've found mostly cited is this article: http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/
which is summarized:

Let's examine why this is so. In short, the problem with Service Locator is that it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.

So basically it doesn't concerns you - all your errors are run-time errors in PHP. (Or unitTests run time error if you are smart :D).

Anyway you can turn every pattern into it's anti-version when overusing it. Think each time if some kind of dependency injection (DI) or other Inversion of Controll (IoC) fits you better.


问:
Interface design - Parameter choice
Situation:

Is it better to have one or few parameters that supply more than enough information for the intended process or should you have more specific parameters that provide just enough information?

When making parameters more specific, if the process of making them more specific means including business rules/logic or heavy coupling with a very specific class is required should it still be done?

Example:

In the case of an Interface:

```<code>public interface IQuestion
{
    // Specificity in Interface parameters increases Coupling right?
    void MyFunction(IPrincipal user, string destination);

    // Is this any better? It allows me to be more flexible in what I'm doing
    // Inside these functions but it also makes them even more coupled right?
    void MyFunction(ControllerContext context);
}
</code>```

Question:

Are there general rules or cases where it's specifically better to do it one way over the other?

答:
Is it better to have one or few parameters that supply more than enough information for the intended process

"More than enough" is the red flag here.

When paying in a store, you don't give your entire wallet so that the cashier takes cash out of it. The cashier doesn't really need to know what your wallet is like, or look at pictures of your kids, and a customer might have no wallet whatsoever. Programs should work in a similar manner.

By passing bundled values that contain (or could contain) more information that necessary you are breaking encapsulation (called functions have access to data that's not of their business), plus it obfuscates the design because there's no clear-cut contract. It's not obvious what the called code actually needs and what it doesn't need just by looking at it, you have to look up its implementation to find out. You don't know what exactly is expected from your ControllerContext to be of any use for MyFunction. It may blow up in runtime.

Of course if User and destination come together, then they simply belong in one class and there's no point in splitting them everywhere. But there's that "more than enough" notion that indicates this is not the case...

Title: Interface design - Parameter choice


答:
It's a balance.

In general, having specific interfaces is better than general interfaces. Functions should not know more than they need to know to work.

But also, in general, it isn't good to have piles of interfaces that are only ever used in one place.

So you need to balance making specific interfaces for your needs and using existing interfaces even though they don't quite fit. Thankfully, if you're doing things right, this comes up infrequently. If your objects are simple and have a single responsibility, then it's uncommon for functions to only need part of that object.

Title: Interface design - Parameter choice

Body:
Situation:

Is it better to have one or few parameters that supply more than enough information for the intended process or should you have more specific parameters that provide just enough information?

When making parameters more specific, if the process of making them more specific means including business rules/logic or heavy coupling with a very specific class is required should it still be done?

Example:

In the case of an Interface:

```<code>public interface IQuestion
{
    // Specificity in Interface parameters increases Coupling right?
    void MyFunction(IPrincipal user, string destination);

    // Is this any better? It allows me to be more flexible in what I'm doing
    // Inside these functions but it also makes them even more coupled right?
    void MyFunction(ControllerContext context);
}
</code>```

Question:

Are there general rules or cases where it's specifically better to do it one way over the other?


问:
Instructions in ISA and microinstructions?

Is it correct that:

a microinstruction is what can be executed directly on hardware?

an instruction in ISA either can  run on hardware (in this case, the instruction is a microinstruction?), or must be interpreted by a microprogram to be a sequence of microinstructions to  run on hardware?

From Tanenbaum's Structured Computer Organization, are "instructions", "register-memory instructions" and
"register-register instructions" mentioned in the following quote
microinstructions or instructions in ISA?

Most instructions can be divided into one of two categories: register-memory or register-register.

Register-memory instructions allow memory words to be fetched into registers, where, for example, they can be used as ALU inputs
  in subsequent instructions. (‘‘Words’’ are the units of data moved
  between memory and registers. A word might be an integer. We will
  discuss memory organization later in this chapter.) Other
  register-memory instructions allow registers to be stored back into
  memory.

A typical register-register instruction fetches two operands from the registers, brings them to the ALU input registers, performs
  some operation on them (such as addition or Boolean AND), and stores
  the result back in one of the registers. The process of running two
  operands through the ALU and storing the result is called the data
  path cycle and is the heart of most CPUs. To a considerable extent,
  it defines what the machine can do. Modern computers have multiple
  ALUs operating in parallel and specialized for different functions.
  The faster the data path cycle is, the faster the machine runs.

Is the "instruction" in a fetch-decode-execute cycle mentioned in
the following quote a microinstruction or an instruction in ISA?

If "instruction" means a microinstruction, what is a "cycle" for an instruction in ISA when it needs to be interpreted by a microprogram?

When running a register-memory instruction (as in part 2) to fetch memory words into registers, does it call itself to fetch itself from memory into the instruction register in step 1?

The CPU executes each instruction in a series of small steps. Roughly speaking, the steps are as follows:

Fetch the next instruction from memory into the instruction register.

Change the program counter to point to the following instruction.

Determine the type of instruction just fetched.

If the instruction uses a word in memory, determine where it is.

Fetch the word, if needed, into a CPU register.

Execute the instruction.

Go to step 1 to begin executing the following instruction.

This sequence of steps is frequently referred to as the
  fetch-decode-execute cycle.

When talking about RISC or CISC, are they referring to microinstructions, or instructions in ISA?
Thanks.

答:
I agree with your interpretation. And if an ISA instruction ties to a single microinstruction, I would still call the instruction an instruction and the microinstruction a microinstruction, even knowing that there's a 1:1 tie. There are all sorts of chip architectures, but I imagine that internally there are differences in naming and things are kept separate that way, e.g. a chip designer might say something like "the MOV instruction implementation consists solely of invocation of the _mov microinstruction". I'm making up my own naming convention here; the point is that there are still two different entities here, even if they happen to correspond 1:1.

Those operations would be instructions; whether they are implemented as single microinstructions or as microprograms, they are still conceptually instructions.

Those operations would also be instructions; the CPU will never have to "fetch" a
microinstruction. It already has the correct microinstructions necessary for any given instruction it fetches burned into its circuit design.

In a pure RISC architecture, there is no instruction / microinstruction distinction.
Each instruction is basically a single microinstruction, although the term
"microinstruction" would not typically by used (since it's not necessary to draw such a distinction). When talking about a CISC device, I'd imagine that people would talk mostly about instructions; if they're referring to the internal microinstructions (which are less likely to be a topic of everyday discussion, in my experience), then people will explicitly say "microinstruction".


答:
I think I have another take on it.

The faculty and staff application is working and is in use.

Changing it to create a student application has a large risk.

I expect that there are few automated system tests for the faculty and staff application.

They will likely run on different servers, so that the student application does not slow down the staff application.

They may have different release and test cycles.

Sooner or later the layout and UI will need to be different between the two applications.

It is possible to share code between applications without having to put it all in one application.

(Some version control systems allow each application to have different versions of the shared code while enabling you to remain sane.)

However I would start by putting the shared code in a common lib, and creating sub classes for each app as needed.    A dependency injection system will be to be used, so an application can control navigation between views with having to have all views knowing about both applications.

Title: How to sell DRY architecture


问:
domain driven design value object behavior
I recently finished Steve Smith and Julie Lerman's excellent Pluralsight course on Domain Driven Design, and I'm applying the training to a project. I have what I think is a good candidate for a value object: MeasurementSpecification. In the problem domain, a measurement specification always has a nominal value, a minimum tolerance, and a maximum tolerance. A model may look something like this:

```<code>public class MeasurementSpecification
{
    public Decimal NominalValue { get; private set; }
    public Decimal UpperToleranceLimit { get; private set; }
    public Decimal LowerToleranceLimit { get; private set; }

    ...setters and behaviors...
}
</code>```

And entities as follows:

```<code>public class WidgetDescription // may be a candidate as another value object, but that's probably another discussion.
{
    public int Id {get; private set;}
    public String Description {get; private set;}
    public MeasurementSpecification Specification {get; private set;}
    ...setters and behaviors...
}

public class Widget
{
    public int Id {get; private set;}
    public WidgetDescription WidgetDescription {get; private set;}
    public decimal MeasurementValue {get; private set;}
    ...setters and behaviors...
}
</code>```

I'm struggling with which class should have the responsibility of validating that a measurement value is within spec. My first inclination is to assign the behavior to the MeasurementSpecification since other entities might also have the MeasurementSpecification value object as one of its properties. An updated model might look like:

```<code>public class MeasurementSpecification
{
    ...

    public Boolean IsWithinSpec(Decimal measurementValue)
    {
        return (measurementValue >= LowerToleranceLimit && measurementValue <= UpperToleranceLimit) ? true : false;
    }
}
</code>```

But I could also see why the Widget entity might have its own behavior of validating its own measurement value against a specification:

```<code>public class Widget
{
    ...
    public Boolean IsWithinSpec()
    {
        return this.WidgetDescription.MeasurementSpecification.IsWithinSpec(this.MeasurementValue)
    }
}
</code>```

Is the approach of including the behavior in both places over-complicating things? Am I missing something?

答:
The suggested IsWithinSpec in Widget-Class knows too much implementation detail about the WidgetDescription-class, e.g. that it contains a MeasurementSpecification. A so called TrainWreck. You could instead create a method in WidgetDescription-class and delegate there.

```<code>public class Widget
{
    ...
    public Boolean IsWithinSpec()
    {
        return this.WidgetDescription.IsWithinSpec(this.MeasurementValue)
    }
}

public class WidgetDesciption
{
    ...
    public Boolean IsWithinSpec(Decimal measurementValue)
    {
        return this.MeasurementSpecification.IsWithinSpec(measurementValue)
    }
}
</code>```

This will reduce unncessecary dependencies and make your code easier to test and you will need less mocking when testing.

hth.

Body:
The suggested IsWithinSpec in Widget-Class knows too much implementation detail about the WidgetDescription-class, e.g. that it contains a MeasurementSpecification. A so called TrainWreck. You could instead create a method in WidgetDescription-class and delegate there.

public class Widget
{
    ...
    public Boolean IsWithinSpec()
    {
        return this.WidgetDescription.IsWithinSpec(this.MeasurementValue)
    }
}

public class WidgetDesciption
{
    ...
    public Boolean IsWithinSpec(Decimal measurementValue)
    {
        return this.MeasurementSpecification.IsWithinSpec(measurementValue)
    }
}

This will reduce unncessecary dependencies and make your code easier to test and you will need less mocking when testing.

hth.


答:
1)
An Instruction Set Architecture defines the interface that is used to program a processor.  Note that this does not define the implementation.  When a CPU designer goes about designing the processor, they may implement this ISA in various different ways.  In fact, the various Intel processors have each implemented the x86 ISA in many different ways over the years.

Computer architecture is generally delineated around an ISA.  Computer microarchitecture is very specific to a particular processor.  For example, a Pentium vs. a Pentium Pro implement for the most part the exact same instruction set, i.e. the x86 ISA.  But their microarchitectures were drastically different. (The Pro was out of order for example).

One of the methods often used to get pipelines to be very fast is to reduce the more complex instructions to microinstructions.  These are used by the "back-end" of the processor, which is the part that has one or more execution units.

Therefore, the point of the two types of instructions ISA instruction vs. microinstruction has to do with whether you are discussing the ISA, i.e. the interface, or the microarchitecture, i.e. the implementation.

2)
As far as your second question, Tanenbaum was almost certainly talking about ISA level instructions because his books are about computer architecture.  Microarchitecture is much more hardware designer centric.  See John Stokes, "Inside the Machine" if you are interested in microarchitecture.

3)
For most real processors, fetch-decode-execute is entirely too simplistic to describe what really goes on inside.  However, from an ISA point of view, it defines a good abstraction to the steps an instruction takes.

The instruction fetch is done by dedicated hardware, so it is different from the load instruction data fetch.  Usually there are actually two bus masters, instruction and data.  These buses often have their own caches.  In some cases, i.e. harvard architectures, the data and instruction memory maps are entirely separate.

4)
RISC vs. CISC is entirely regarding the ISA, i.e. the interface.  However, the RISC mindset of using a reduced instruction set is very much to simplify the microarchitecture.  The effect is that the microarchitectural instructions are generally exactly the same as the ISA instructions in RISC processors.

Title: Instructions in ISA and microinstructions?

Body:
Is it correct that:

a microinstruction is what can be executed directly on hardware?

an instruction in ISA either can  run on hardware (in this case, the instruction is a microinstruction?), or must be interpreted by a microprogram to be a sequence of microinstructions to  run on hardware?

From Tanenbaum's Structured Computer Organization, are "instructions", "register-memory instructions" and
"register-register instructions" mentioned in the following quote
microinstructions or instructions in ISA?

Most instructions can be divided into one of two categories: register-memory or register-register.

Register-memory instructions allow memory words to be fetched into registers, where, for example, they can be used as ALU inputs
  in subsequent instructions. (‘‘Words’’ are the units of data moved
  between memory and registers. A word might be an integer. We will
  discuss memory organization later in this chapter.) Other
  register-memory instructions allow registers to be stored back into
  memory.

A typical register-register instruction fetches two operands from the registers, brings them to the ALU input registers, performs
  some operation on them (such as addition or Boolean AND), and stores
  the result back in one of the registers. The process of running two
  operands through the ALU and storing the result is called the data
  path cycle and is the heart of most CPUs. To a considerable extent,
  it defines what the machine can do. Modern computers have multiple
  ALUs operating in parallel and specialized for different functions.
  The faster the data path cycle is, the faster the machine runs.

Is the "instruction" in a fetch-decode-execute cycle mentioned in
the following quote a microinstruction or an instruction in ISA?

If "instruction" means a microinstruction, what is a "cycle" for an instruction in ISA when it needs to be interpreted by a microprogram?

When running a register-memory instruction (as in part 2) to fetch memory words into registers, does it call itself to fetch itself from memory into the instruction register in step 1?

The CPU executes each instruction in a series of small steps. Roughly speaking, the steps are as follows:

Fetch the next instruction from memory into the instruction register.

Change the program counter to point to the following instruction.

Determine the type of instruction just fetched.

If the instruction uses a word in memory, determine where it is.

Fetch the word, if needed, into a CPU register.

Execute the instruction.

Go to step 1 to begin executing the following instruction.

This sequence of steps is frequently referred to as the
  fetch-decode-execute cycle.

When talking about RISC or CISC, are they referring to microinstructions, or instructions in ISA?
Thanks.


问:
Why can't a compiler avoid importing a header file twice by its own?
New to C++! So I was reading this: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

Header guards

Because header files can include other header files, it is possible to
  end up in the situation where a header file gets included multiple
  times.

So we make preprocessor directives to avoid this. But I'm not sure - why can't the compiler just... not import the same thing twice?

Given that header guards are optional (but apparently a good practice), it almost makes me think that there are scenarios when you do want to import something twice. Although I can't think of any such scenario at all. Any ideas?

答:
One difficulty with automatic duplicate-header exclusion is that the C standard is relatively silent on the subject of what include filenames mean.  For example, suppose the main file being compiled contains directives #include "f1.h" and #include "f2.h", and the files found for those directives both contain #include "f3.h".  If f1.h and f2.h are in different directories, but were found by searching include paths, then it would be unclear the #include directives within those files were intended to load the same f3.h file, or different ones.

Things get even worse if one adds in the possibilities of include files including relative paths.  In some cases where header files use relative paths for nested include directives, and where one wishes avoid making any changes to supplied header files, it may be necessary to have a header file duplicated in multiple places within a project's directory structure.  Even though multiple physical copies of that header file exist, they should be regarded semantically as though they are a single file.

If the #pragma once directive allowed an identifier to follow once, with the semantics that the compiler should skip the file if the identifier matches one from an earlier-encountered #pragma once directive, then the semantics would be unambiguous; a compiler which could tell that an #include directive would load the same #pragma once-tagged file as an earlier one, it could save a little time by skipping the file without opening it again, but such detection would not be semantically important since the file would be skipped whether or not the filename was recognized as a match.  I'm unaware of any compilers working that way, however.  Having a compiler observe whether a file matches the pattern #ifndef someIdentifier / #define someIdentifier / #endif [for that ifndef] / nothing following and treating such a thing as equivalent to the above #pragma once someIdentifier if someIdentifier remains defined, is essentially as good.


答:
The real issue in this case is long-term maintainability of two separate codebases vs. a single codebase. Convincing people who do not understand the problem requires persuasion. Does your school have a computer science department? How about a business school or management department? Some internal support from an instructor would be good.

In short, the issue is this: write two applications, you end up with two codebases, which means potentially twice as much effort to maintain as long as these applications are in use. Sharing modules between codebases can ameliorate this problem to some extent, but if you are going that far with re-factoring your existing application, just re-factor/re-architect it into a single application.

Managers will push back against what they will see as extra effort for no functional gain, and you need to convince them that the payoff comes over the long term. It is also incumbent on the technical team to do a good enough job on the application to validate the argument you are making, so if you decide to push for the solution you want, make sure the team can back it up.

There might be merit to the argument that it will be complicated to change the existing application to accommodate different permission sets, but the complexity being discussed is a problem that should have been dealt with before the first application was built. If the requirement for providing the functionality to students was known ahead of time, it was a mistake not to architect for it. Do not let a past mistake keep the team from making the right decision for the next stage of the project.

Title: How to sell DRY architecture


问:
How to approach refactoring an existing web application?
I've been reading and thinking a lot lately, and I've come to the conclusion that I maybe I should rethink my web development strategy. I'm doing a lot of on-the-fly programming, and in the 2 years I've been working on a PHP web application, what might have begun as a little tool became quite the big project. But there is a ton of legacy code from me and my predecessor, snippet of code that might have make sense at the time, but now I'm questioning the usefulness of said code in the form it is actually. Furthermore so such things like unit testing and Test-Driven Development wasn't in my scope until quite recently.

So how would you approach refactoring the web application? What would be the things I should look for and in which order? What about browser game versus functional web app? Would there be then difference in the approach?

答:
There's a great book about this called "Working Effectively with Legacy Code" by Michael Feathers.  Let's face it, we all have legacy code.

The main thing is to test-drive the new code that you're creating.  As you have to touch other pieces of code, you'll find opportunities to get those under test as well.  It's a long slow process, but if you go about it systematically, you can really improve the overall product over time.


问:
Why is DRY important?
Quite simple, why would I want to write code that works for all cases and scalable data when all I need to do is repeat the same process a few times with a few minor tweaks?

I'm unlikely to need to edit this again any time soon.

It looks like a lot of less work to just go...

```<code>function doStuff1(){/*.a.*/}
function doStuff2(){/*.b.*/}
function doStuff3(){/*.c.*/}
</code>```

And if I ever need to add something...

```<code>function doStuff4(){/*.d.*/}
</code>```

And if I need to remove it, I remove it.

It's harder to figure out how to make all of those into one straight-forward pattern that I can just feed data into and deal with all the cases, and make a bunch of changes I don't feel like I'm ever going to have to do.

Why be DRY when it looks like a quick cut+paste is going to be so much less work?

答:
The phraseology "don't repeat yourself" is a little oversimplistic.  What's important is "avoid having one piece of potentially-changeable information encapsulated in two independent places."

If a program is supposed to process widgets, each with three woozles, and are many loops of the form

```<code>for (i=0; i<3; i++)
  thisWidget.processWoozle(i);
</code>```

then the expectation that the widgets are expected to contain three woozles would be encapsulated in each of those loops, and updating the code to accommodate any other number of woozles per widget could be difficult.  By contrast, if one were to say

```<code>#define WOOZLES_PER_WIDGET 3
</code>```

and each loop were rewritten

```<code>for (i=0; i<WOOZLES_PER_WIDGET; i++) ...
</code>```

such a design might make it very easy to change the number of woozles per widget.

It's important to note, however, that while it's desirable to consolidate information like the number of woozles per widget to a single point, it's not always practical.  Sometimes it may be necessary to hard-code logic which will only be work if things are a particular size.  For example, if each woozle has a value and one wants to find the median associated with a particular widget, it may be possible to sort the values and take the middle one, and such an approach would work with any number of woozles, but logic which is hand-written specifically to find the median of three items could be significantly faster.

While having a WOOZLES_PER_WIDGET constant may make code more readable, it should be commented to make clear that its value cannot be changed without making other adjustments to program logic.  In that case, the logic which is hard-coded for three items and the constant WOOZLES_PER_WIDGET would both be duplicating the information "each widget has three woozles", but the benefits of such duplication (greater execution speed) could outweigh the cost.

Title: Why is DRY important?

Body:
The phraseology "don't repeat yourself" is a little oversimplistic.  What's important is "avoid having one piece of potentially-changeable information encapsulated in two independent places."

If a program is supposed to process widgets, each with three woozles, and are many loops of the form

for (i=0; i<3; i++)
  thisWidget.processWoozle(i);

then the expectation that the widgets are expected to contain three woozles would be encapsulated in each of those loops, and updating the code to accommodate any other number of woozles per widget could be difficult.  By contrast, if one were to say

#define WOOZLES_PER_WIDGET 3

and each loop were rewritten

for (i=0; i<WOOZLES_PER_WIDGET; i++) ...

such a design might make it very easy to change the number of woozles per widget.

It's important to note, however, that while it's desirable to consolidate information like the number of woozles per widget to a single point, it's not always practical.  Sometimes it may be necessary to hard-code logic which will only be work if things are a particular size.  For example, if each woozle has a value and one wants to find the median associated with a particular widget, it may be possible to sort the values and take the middle one, and such an approach would work with any number of woozles, but logic which is hand-written specifically to find the median of three items could be significantly faster.

While having a WOOZLES_PER_WIDGET constant may make code more readable, it should be commented to make clear that its value cannot be changed without making other adjustments to program logic.  In that case, the logic which is hard-coded for three items and the constant WOOZLES_PER_WIDGET would both be duplicating the information "each widget has three woozles", but the benefits of such duplication (greater execution speed) could outweigh the cost.


问:
Is initializing a char[] with a string literal bad practice?
I was reading a thread titled "strlen vs sizeof" on CodeGuru, and one of the replies states that  "it's anyways [sic] bad practice to initialie [sic] a char array with a string literal."

Is this true, or is that just his (albeit an "elite member") opinion?

Here is the original question:

```<code>#include <stdio.h>
#include<string.h>
main()
{
    char string[] = "october";
    strcpy(string, "september");

    printf("the size of %s is %d and the length is %d\n\n", string, sizeof(string), strlen(string));
    return 0;
}
</code>```

right. the size should be the length plus 1 yes?

this is the output

the size of september is 8 and the length is 9

size should be 10 surely. its like its calculating the sizeof string before it is changed by strcpy but the length after.

Is there something wrong with my syntax or what?

Here is the reply:

It's anyways bad practice to initialie a char array with a string literal. So always do one of the following:

```<code>const char string1[] = "october";
char string2[20]; strcpy(string2, "september");
</code>```

答:
One thing that neither thread brings up is this:

```<code>char whopping_great[8192] = "foo";
</code>```

vs.

```<code>char whopping_great[8192];
memcpy(whopping_great, "foo", sizeof("foo"));
</code>```

The former will do something like:

```<code>memcpy(whopping_great, "foo", sizeof("foo"));
memset(&whopping_great[sizeof("foo")], 0, sizeof(whopping_great)-sizeof("foo"));
</code>```

The latter only does the memcpy.  The C standard insists that if any part of an array is initialized, it all is.  So in this case, it's better to do it yourself.  I think that may have been what treuss was getting at.

For sure

```<code>char whopping_big[8192];
whopping_big[0] = 0;
</code>```

is better than either:

```<code>char whopping_big[8192] = {0};
</code>```

or

```<code>char whopping_big[8192] = "";
</code>```

p.s. For bonus points, you can do:

```<code>memcpy(whopping_great, "foo", (1/(sizeof("foo") <= sizeof(whopping_great)))*sizeof("foo"));
</code>```

to throw a compile time divide by zero error if you're about to overflow the array.

Body:
One thing that neither thread brings up is this:

char whopping_great[8192] = "foo";

vs.

char whopping_great[8192];
memcpy(whopping_great, "foo", sizeof("foo"));

The former will do something like:

memcpy(whopping_great, "foo", sizeof("foo"));
memset(&whopping_great[sizeof("foo")], 0, sizeof(whopping_great)-sizeof("foo"));

The latter only does the memcpy.  The C standard insists that if any part of an array is initialized, it all is.  So in this case, it's better to do it yourself.  I think that may have been what treuss was getting at.

For sure

char whopping_big[8192];
whopping_big[0] = 0;

is better than either:

char whopping_big[8192] = {0};

or

char whopping_big[8192] = "";

p.s. For bonus points, you can do:

memcpy(whopping_great, "foo", (1/(sizeof("foo") <= sizeof(whopping_great)))*sizeof("foo"));

to throw a compile time divide by zero error if you're about to overflow the array.


问:
What would an anti-tree look like?
I am wondering if the Tree data structure has a dual. Something that 'starts at the leaves and converge on the root'.

If so, what's it called?

Maybe I'm missing something completely obvious. I could not find anything useful is searching on Google. Maybe that's because I'm not a native English speaker.

答:
I'm not really sure what the meaningful difference would be, nor how you would go about implementing such a thing. The two ways I have seen trees implemented is either with an array or a by reference.

In an array implementation, the first element is the root and child nodes can be located by a fairly simple transformation of the parent's index. You could presumably reverse that easily enough so that the first element is the right most leaf and find the parent of any child by use of the array length and index. The only problem is that the array length and thus tree size is fixed and it is much harder to dynamically increase the size.

It's much easier to do with references though. You could easily create an AntiTree class that, say, provides a list of all leaves, and then each leaf references it's parent, and so on, until you reach the root which has no parent. But that just seems like a different traversal order.

Just had another thought. In terms of what to call it, isn't what you are describing just a funnel?

Title: What would an anti-tree look like?


答:
If you view a tree as undirected graph without loops, then the opposite of that is just the same tree - it's completely isomorphic.

If you speak about an actual data structure which uses directed graphs, then, again, it can be just named "tree" which has it's links inverted: normally you have children referencing their parents (like is SQL database you'd have parent_id column referencing id column of the same table), but here you have parents have references of all their children. That would require having an array of references (parent->child), whereas in "normal" trees each element has just one reference (child->parent).

In git, for example, "true" merge commits have multiple parents, which is just what you've described. Although, git repository generally is not a tree, but some of its' parts can be.

EDIT: from Wikipedia:

tree data structure can be defined recursively (locally) as a collection of nodes (starting at a root node), where each node is a data structure consisting of a value, together with a list of references to nodes (the "children"), with the constraints that no reference is duplicated, and none points to the root.

That means that parent-child relations in my git and SQL examples are actually considered inverted. As @Wyzard says, it is actually an "anti-tree" you've described. Yet, it is still called "tree".

Inversion in these examples allows using just one reference (to a parent) per node instead of list of references (to children). Also, it is convenient to add children in one step, without having to add a reference into a children references list of its' parent.

Title: What would an anti-tree look like?

Body:
I am wondering if the Tree data structure has a dual. Something that 'starts at the leaves and converge on the root'.

If so, what's it called?

Maybe I'm missing something completely obvious. I could not find anything useful is searching on Google. Maybe that's because I'm not a native English speaker.


答:
I'm not sure of an exact mathematical concept for what you are describing, but it does seem to match pretty closely to the concept of a directed acyclic graph aka DAG. Many programmers actually use DAGs every day in their work, in the form of version control software. Git (and Mercurial and etc) commit histories form a DAG. We track the leaf nodes (in Git, the refs and branches; in Mercurial, the heads; etc) and traverse back to the root node. Each node has a pointer to to its parent, rather than the other way around.

A DAG does not need to be strictly tree-like in that it can have nodes with multiple parents (a merge commit in Git, for example).

Title: What would an anti-tree look like?


问:
Can I modify existing GPL software to use a proprietary (closed-source) library and then distribute one or both?
Say I have GPL software A and proprietary library B. I modify A to use B. Am I then free to distribute A by itself? The GPL FAQ seems to indicate that is there case here:
https://www.gnu.org/licenses/gpl-faq.html#FSWithNFLibs

Now what if I already own the license to B. Am I now able to distribute both A and B together even though B is closed-source? I don't see how I could be forced to license B as GPL since it already existed independent from and is in no way derived from A.

All linking to B is done dynamically at runtime.

答:
First disclaimers
1. I'm not a lawyer - and this isn't a forum for a legal advice
2. if you ask 5 different IP lawyers RE GPL compliance, you will likely get 5 different answers. It has not been really tested much in US courts AFAIK.

With that, here's my take. In short, I believe you can release A by itself under GPL (provided you meet the source code availability and other license requirements).  The fact you made modification to A to call B means you also need to release your modification to A under GPL license, but it does not mean you need to also release B under GPL, or release B with A.

The license of B (whether GPL or not, or proprietary) or even how you call B (dynamic linking vs static) is irrelevant here because it's A calling B, not the other way around (so one cannot say B is a derivative of A).  You are still preserving the freedom of the users - which is really the intent and essence of the GPL license.  Users can make changes to the source code of A to use something other than B should they want to.


答:
There sorta kind of is and isn't! But we need to refine our terminology to understand what's going on.

We have a hierarchy like this in graph theory, which flows from general at the top to more specific/restricted at the bottom:

Graph: a collection of nodes (vertex) and paths (connections between vertex)

Connected graph: a collection of nodes where you can pick any one start node and reach any other end node. The choice of start and end is arbitrary.

Tree: A connected graph where there is one and only one unique path between any one start node and any one end node. There are no alternate paths which do not backtrack (visit a node twice).

Rooted Tree: Just as a tree, but there is one specific item picked as being the root. From these we also define leaves, which is any node that must be an end-node when visited from the root - without visiting a node twice once you hit a leaf you cannot go anywhere, and the path is terminated. Leaves can also be called a "terminal vertex".

Note that even a rooted tree does not necessarily have direction - you are free to start at a leaf and proceed to the root, etc.

If a tree is implemented as a single-linked data structure, this can be thought of as a directed tree if there is no back-link available - once you leave the root for one of the connected nodes, you can't get back!

But such an implementation of a tree is not necessary in the definition of a tree! One can implement a tree with double-linked lists, such that you are free to do things like move towards the root (often referred to as a Parent) or away from the root (Child).

So if you want a data structure where you can start at a leaf and work to the root, you just need one that supports a "visit parent" function. You can also trivially define a system which does not permit moving from root (Parent) to Child, only from Child to Parent, and this sounds like what you are looking for. You basically just remove "visit child" functionality.

However, I am not aware of any formal name for such a structure, or what use such a structure would have. Trees that start from a root are useful, and ones that allow walking up and down are useful, but ones that only allow one-way movement towards the root is of such specialized/limited usefulness that I doubt it has a special name reserved for it. But I suppose anything is possible!

As a practical matter, you can easily implement one from existing directed trees or directed rooted trees.

Title: What would an anti-tree look like?


答:
From a purely technical standpoint, an anti-tree is what you have every time you choose to represent a tree not by equipping each parent node with an array of pointers to its child nodes, but by equipping each child node with a single pointer to its parent node.

Trees are commonly represented this way, for example, in relational databases.

Title: What would an anti-tree look like?


问:
Why does Jenkins warn you if you tell it to check for changes every minute?
In the past when I've set up Jenkins to look for version control changes every second by using the cron format of "* * * * *" (or something like that).  When you do this, it gives you a warning and asks if you meant to say something like once a day.  </p>

<p>My question is, why would checking once per minute ever be a bad thing?  The only bad aspect that comes to mind is that it may be a performance issue.  Otherwise, I would want my continuous integration server to always be checking for changes as frequently as possible so that I can know as soon as possible if an error got introduced.  Is there a perspective I'm not seeing?  </p>

答:
There are two things here - the client (in this case Jenkins) and the server (svn or git or something else).

As the client, asking every minute can consume a bit of resources - network and disk on the server, not to mention its own internal builds that compete with local resources for checking if anything has been updated.

At the server side, having a half dozen projects that get polled every minute can likewise be consuming in resources (disk and network) and can start to contend with other client updates (like your developers).

The thing is, if you want to start the build as soon as possible, there are other options for this.  You can do a push instead of a pull.  For example, on Stack Overflow: Jenkins CI: How to trigger builds on SVN commit and How to configure Git post commit hook in which the act of pushing a commit to the server will trigger a Jenkins build.  It will never need to poll (much less every minute) to see if it needs to build because the server tells it to do so when it needs to.

As a follup to all this, I would suggest reading Polling must die: triggering Jenkins builds from a git hook which takes a more opinionated take on the issue.

One should look at the reason behind the desire to have the server polling every minute. This is what Jenkins, in part, seeks to address with the warning. If you want "building as soon as a commit happens" then hooks are the best technology to use for both the build server and the source of the data.

On the other hand, on many projects, a delay on a build isn't as big of an issue as a delay of a few minutes would make it out to be. On several of the projects I've worked on a full test and analysis (as done on the CI server because it took too long to run on a developer's machine) took a good 10-15 minutes if the build server wasn't being taxed with other builds at the time (all the unit tests and static code analysis on a 1.5M SLOC project, then fire up a HSQLDB and jetty instance and run another set of tests...).  Doing the polling every half hour was more than sufficient (and if a developer wanted the build to start now so that it would be done before he or she wanted to go to lunch or leave for the day and know with confidence they wouldn't incur the wrath of a broken build upon return... well, there is always the "build now" button)


问:
Performing data operations that involve separate applications and data sources
I'm designing an enterprise application that produces output based on some input data from another application.  In this case, I happen to have also built and thus do control the source application and data, database structure, etc., but this question also applies to cases where I am using input data from a third-party application, so I'll assume that going forward.

The new application should only produce output once for a given set of input data; it will pull data from the source, produce output, and maintain state so that the same input data is not processed the next time it runs.

What I'm wondering about is what is a good design approach to take in cases where I need to store state so that I'm not pulling the entire universe of source data when I only need to operate on a small subset of that data.

Three options I can think of are:

Modify the schema of the third-party source database so I can store my state there.

Query the data via a join between the third-party database and my new database and filter the results within that query based on state that is stored in the new database.

Warehouse the source data within my new database and perform all queries against the warehoused data.

I have worked with commercial enterprise applications that use all of these approaches, but each of them has its downsides:

With option 1, one obvious downside is that modifying a third-party database is, at best, discouraged by most vendors and, at worst, explicitly forbidden in license agreements.  Furthermore, future vendor updates to the schema could wipe out data or fail due to conflicts caused by your modifications.  The bottom line for me, though, is that I just don't want to store data for a "destination" application in a "source" application's database, regardless of whether I "own" both databases or not, but especially if the source is a third-party application.  If the data is not used by the application itself, it doesn't belong in its database.

With option 2, one downside is that the databases may be migrated to different servers, and if joins are not constructed properly with fully-qualified object names -- including dynamically-provided DB server names (because of the aforementioned possibility of them being migrated to different servers) -- then the application will break.  Another downside is that the source data might not even be stored in the same format as the new database (e.g. a different DBMS) thus precluding the possibility of a join.  Most importantly for me, though, is the fact that this approach violates Separation of Concerns because either the data layer has to perform some awkward and arguably-inefficient surgery to rend the two entities into separate domain objects or the domain layer has to have some gnarly beast hybrid of the two disparate entities.  Either way, it smells.

Option 3 sounds the best to me, but it still has the downside that there is overhead involved in populating and maintaining the warehouse.  Some "process" has to do this.  Where does that process run...from some middle-tier server?  How often does it run, and what happens if your application wants data that hasn't been updated yet?  Who administers it?

Does anyone know of another approach I haven't considered, or can anyone offer any insight into any of the above approaches I have considered (for instance, suggest modifications to the approaches that preclude the downsides or explain to me why one approach is best despite its downsides)?

答:
There are some questions to be asked:

Does external data have a timestamp PK or an incremental PK that would allow you to know what were the last data items you already processed?

Do you need to process only new data or old data that has been modified also?

If the external data has a timestamp PK or incremental PK, the state you need would be the last timestamp or incremental key value processed. You can either store it in one table in the destination database.

I would suggest the following approach:

A crontab job A reads external database (the consumer should be the responsible of pulling the data) and populates a temporal table.

Another cron job B reads that data, which is already in your database, and processes it, generating output data in the formal tables. Then it saves the "state" in a table (the last timestamp or incremental key of external database processed).

Another cron job C deletes from the temporal table any data that was already processed (you can infer which rows to delete by comparing with the "state" value saved by job B)

This approach works for new data only. If you need to process old data (data that was previously processed but has changed in the origin) then things get complicated.

Note that this approach is different from your third one (datawharehouse) in that data is only stored temporarily.


答:
You should be explicit when talking to your team that this is a trade-off between initial time-to-market of a first version of the student site and the total cost of ownership over the lifetime of the system.

I have seen a real system which evolved over a decade built out of PHP where clients have a extranet micro-site where they can upload/download data/reports to a backend system. They started out with no source control and just literally folder copied the last custom micro-site to start the next customer micro-site and made enhancements only to the latest site they were working on.

A decade later they had hundreds of semi-bespoke micro-sites all on different versions of their code. Remarkably the system was (and is still) successful. This is because each micro-site was "good enough" for the client to do their data entry which was stable for years. The fact that each micro-site had per-client changes was even made into a selling point as "bespoke client engagement".

The key point was that they never had to go back and retest any older micro-sites when they changed anything being worked on for the latest new client. The fact that they could give an inconsistent experience across all clients meant they didn't have to maintain any common code (only some common data import/export logic to the backend systems which they eventually managed to generalise as highly configurable backend code with a flat file interface).

I give this example as there is always an exception which demonstrates the general rule; most site really must give a consistent, "latest and greatest" experience to all users and it wouldn't be rational nor acceptable to work in the manner just described.

With your application if you have lots of logic encoded into the page, with no proper tempting engine, no separated business layer and data access layers, and no isolated data model / object model, with no automated backend unit tests and no automated front-end test, then yes, your colleagues are correct, that leaving what is done alone and starting with a copy, that can rapidly evolve, talking to mostly the same database tables, without going back to fix up and test the existing site, would get a first working prototype up and running much faster than "doing it properly".

Yet after a quick success your employer is going to want to take advantage of their new application to roll-out new features and capabilities which improve the engagement between staff and students. They will expect it to be "one thing" and consistent and seemless not "two things" working hard to stay in sync.

What you need to elaborate is what is the potential long term gain when "doing it properly"; what new common features are the future of the site which justify a shared data model, shared common business logic, templates per user type / user conditional views over the model / logic. If such future requirements exist (which they surely must) then it would be clear that upgrading to an off-the-shelf security/cms framework/engine, putting in a standard conditional templating engine to render the views, designing/enhancing a shared data model, designing common business logic for all users, would get the full end-state experience without twice the code and surely twice the effort and bugs.

I would recommend that you have organise a review of the potential future requirements and suggest going some proof-of-concept work (a few weeks) on coming up with the best approach to best prepare the system to meet those future requirements whilst building out the next phase of the project (i.e. upgrade frameworks/migrate functionality into an opensource cms you can write custom modules to create all bespoke functionality leveraging its framework maturity and user model). I suspect that at the moment people will be focusing on the "upcoming deadline to get the student site live" and thinking about "not doing lots of rework or having to learn something new". So you need to get the customer / boss excited about the target future functionality / end-state and get your team mates excited about "doing it properly" with new exciting new tools and techniques. Then doing the right thing will hopefully become everyones idea. Good luck.

Title: How to sell DRY architecture


答:
The ideal solution would be for your source application to expose a SOA layer to give external applications access to the data.

Failing this (or where the query volume is large and or intensive) then database replication  is a good solution -- always assuming the technology is in place to do this reliably.

Failing the above two solutions I would go for a full data dump! Its easier to code up (often just using DBMS utilities), there are no messy re-synchronization, timing and control issues to deal with. Besides any solution which attempts to pull the latest changes will need a full data dump process for initial load and the inevitable re-sync after operational  screw ups.

Title: Performing data operations that involve separate applications and data sources

Body:
I'm designing an enterprise application that produces output based on some input data from another application.  In this case, I happen to have also built and thus do control the source application and data, database structure, etc., but this question also applies to cases where I am using input data from a third-party application, so I'll assume that going forward.

The new application should only produce output once for a given set of input data; it will pull data from the source, produce output, and maintain state so that the same input data is not processed the next time it runs.

What I'm wondering about is what is a good design approach to take in cases where I need to store state so that I'm not pulling the entire universe of source data when I only need to operate on a small subset of that data.

Three options I can think of are:

Modify the schema of the third-party source database so I can store my state there.

Query the data via a join between the third-party database and my new database and filter the results within that query based on state that is stored in the new database.

Warehouse the source data within my new database and perform all queries against the warehoused data.

I have worked with commercial enterprise applications that use all of these approaches, but each of them has its downsides:

With option 1, one obvious downside is that modifying a third-party database is, at best, discouraged by most vendors and, at worst, explicitly forbidden in license agreements.  Furthermore, future vendor updates to the schema could wipe out data or fail due to conflicts caused by your modifications.  The bottom line for me, though, is that I just don't want to store data for a "destination" application in a "source" application's database, regardless of whether I "own" both databases or not, but especially if the source is a third-party application.  If the data is not used by the application itself, it doesn't belong in its database.

With option 2, one downside is that the databases may be migrated to different servers, and if joins are not constructed properly with fully-qualified object names -- including dynamically-provided DB server names (because of the aforementioned possibility of them being migrated to different servers) -- then the application will break.  Another downside is that the source data might not even be stored in the same format as the new database (e.g. a different DBMS) thus precluding the possibility of a join.  Most importantly for me, though, is the fact that this approach violates Separation of Concerns because either the data layer has to perform some awkward and arguably-inefficient surgery to rend the two entities into separate domain objects or the domain layer has to have some gnarly beast hybrid of the two disparate entities.  Either way, it smells.

Option 3 sounds the best to me, but it still has the downside that there is overhead involved in populating and maintaining the warehouse.  Some "process" has to do this.  Where does that process run...from some middle-tier server?  How often does it run, and what happens if your application wants data that hasn't been updated yet?  Who administers it?

Does anyone know of another approach I haven't considered, or can anyone offer any insight into any of the above approaches I have considered (for instance, suggest modifications to the approaches that preclude the downsides or explain to me why one approach is best despite its downsides)?


答:
I'm not sure the polling resources argument is compelling.  It's a relatively efficient operation on most version control systems, especially if you're just checking and not actually downloading the changes yet.  Although, a push notification is certainly preferable.

Usually it's the building resources that are the limiting factor, depending how frequently commits happen and how long your builds take.  If you start a build too frequently, and your build nodes max out, that can increase the average latency to get results, especially at the busy times.  Also, what can happen is a commit breaks the build, but by the time you get the results, you have several later builds broken by the same bug.  This conditions developers to pay less attention to the CI server.

So if you happen to have fast builds and your build nodes never max out, by all means increase the polling frequency.  If your build nodes are always maxed out and commits always break 3 or 4 builds before you even know it, then decreasing the polling frequency can help.

Title: Why does Jenkins warn you if you tell it to check for changes every minute?

Body:
In the past when I've set up Jenkins to look for version control changes every second by using the cron format of "* * * * *" (or something like that).  When you do this, it gives you a warning and asks if you meant to say something like once a day.  </p>

<p>My question is, why would checking once per minute ever be a bad thing?  The only bad aspect that comes to mind is that it may be a performance issue.  Otherwise, I would want my continuous integration server to always be checking for changes as frequently as possible so that I can know as soon as possible if an error got introduced.  Is there a perspective I'm not seeing?  </p>


问:
Are there memory-memory instructions?
From Tanenbaum's Structured Computer Organization,

Most instructions can be divided into one of two categories: register-memory or register-register.

Register-memory instructions allow memory words to be fetched into registers, where, for example, they can be used as ALU inputs
      in subsequent instructions. (‘‘Words’’ are the units of data moved
      between memory and registers. A word might be an integer. We will
      discuss memory organization later in this chapter.) Other
      register-memory instructions allow registers to be stored back into
      memory.

A typical register-register instruction fetches two operands from the registers, brings them to the ALU input registers, performs
      some operation on them (such as addition or Boolean AND), and stores
      the result back in one of the registers. The process of running two
      operands through the ALU and storing the result is called the data
      path cycle and is the heart of most CPUs. To a considerable extent,
      it defines what the machine can do. Modern computers have multiple
      ALUs operating in parallel and specialized for different functions.
      The faster the data path cycle is, the faster the machine runs.

Are there memory-memory instructions?

Or is a memory-memory "operation" implemented as two register-memory instructions (one for read and the other for write)?
Isn't this inefficient than moving data directly between two places in the same memory without going via a register?

答:
Memory chips do not have a mechanism for transferring data directly from one memory location to another.  Hence, the processor must read the data from memory, and then write it to the new location.

In computer systems having DMA controllers, it is possible to perform memory transfers without involving the CPU.  There are potential complications, such as cache coherency.

Title: Are there memory-memory instructions?


问:
How are declarative languages executed by a computer?
I'm getting introduced to declarative languages and am beginning to love them. In particular Haskell, a functional language, is very expressive, easy to debug. But my question has to do with execution. Are such languages compiled or interpreted? If it is the latter then I would have to choose conventional languages like C++ or Java for performance reasons. But I would love to use declarative languages for their increased productivity and ease of maintenance.
Eager to hear from the esteemed members of this community.</p>

答:
There's no universal answer for all languages; it just depends on what's been implemented for a particular language.  Haskell, in particular, can be either compiled or interpreted.  Some declarative languages may only have interpreters currently, but a compiler could be written in the future.

Also, don't assume that just because a language implementation is interpreted, it's unusable "for performance reasons".  Depending on the application, interpreted code may still be fast enough.


问:
Writing Unit Tests in the Middle
Is unit testing a 100% or not at all kind of deal?

I was browsing through my old projects and started adding features, this time with unit testing.  However, is this ultimately worthless if I'm going to be re-using past components that do not have unit tests?

Do I need to write unit tests for all the previous classes and not bother at all, or is it OK to only write unit tests for the new stuff I'm adding?

答:
Is unit testing a 100% or not at all kind of deal?

Absolutely not!  Start testing the new code you are adding.  You will see immense benefits from doing that, even if some of the older components don't have tests.  As you have to deal with one of those components, or find a bug in it, write a test.  Over time you will get more of the older code under test.

Title: Writing Unit Tests in the Middle


问:
Is ReST useful in Read/Write Operations that involve over 100 Gig
I work in Healthcare and we use SAS to Extract and Transform medical and pharmacy claims data for use in downstream reporting applications.  For a given Report Request(usually 40 are running at a time) we have to extract from various DBMS's and transform the data. Once completed with this ET step, the data is over 100 gig in aggregated form(SAS Tables). This data is indexed and optimized for report consumption.  We don't have to go back to the database after we have extracted the data.

To me using ReST doesn't make much sense in this situation as XML is not very efficient for large data volumes.  But I thought I would ask to see what the rest of the Programmers' world thinks.

答:
The answer discusses in general the aspect of sending large data over HTTP using REST. Make sure you also read the answer by Robert Jack Will which is more specific and suggests a way which makes it possible to avoid sending large data in the first place.

REST has nothing to do with XML: the format of the data, would it be JSON, XML, plain text or binary stream, is irrelevant. For instance, you can serve images (JPEG, PNG...) through REST, which doesn't mean that you need to enclose them in XML.

On the other hand, REST is based on HTTP, and HTTP is indeed suitable for large data transfers. Of course, you have to be careful when configuring both your service and your client to use streams when downloading such large data, instead of loading it in memory.

As for the actual format of the data:

If it is imperative to keep self-documenting structure, use JSON, XML or plain text, but make sure you compress the content at server side before sending it. The choice of the compression algorithm will depend on your platform and the interoperability requirement, given that proprietary formats such as RAR may often achieve better compression ratio (still, make the test with your data to see how well different algorithms perform).

Note that it may not be that easy to find a serializer/deserializer for XML or JSON which will produce/accept a stream instead of a string. In this case, plain text may be your best choice.

If self-documenting structure is not required, binary format may be a better alternative in terms of the size. Still, make an actual comparison between plain text compressed data and binary data to see which one produces smaller result; you may be surprised.