问:
What is early and late binding?
I keep hearing about early and late binding, but I do not understand what they are. I found the following explanation which I do not understand:

Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time.

Could someone please define the two types of binding and compare them?

答:
if you are familiar with function pointers this would be an example.
Functions defined can be said to be Early binding .
whereas if you use Function pointers its late Binding.

```<code>  int add(int x,int y)
  {
    return x+y;
  }
  int sub(int x,int y)
  {
      return x-y;
  }

    int main()
    {
     //get user choice
     int(*fp)(int,int);
     //if add
      fp=add;
     //else if sub
     fp=sub;
     cout<<fp(2,2);
    }
</code>```

here functions add and sub are functions (its address are binded at compile time-linker)

but the function pointer is late binding the fp can call either add or sub depending on user choice [at runtime].

Title: What is early and late binding?

Body:
if you are familiar with function pointers this would be an example.
Functions defined can be said to be Early binding .
whereas if you use Function pointers its late Binding.

  int add(int x,int y)
  {
    return x+y;
  }
  int sub(int x,int y)
  {
      return x-y;
  }

    int main()
    {
     //get user choice
     int(*fp)(int,int);
     //if add
      fp=add;
     //else if sub
     fp=sub;
     cout<<fp(2,2);
    }

here functions add and sub are functions (its address are binded at compile time-linker)

but the function pointer is late binding the fp can call either add or sub depending on user choice [at runtime].


问:
Converting a user management system to use ajax
I am currently building a website, which until quite recently was purely PHP. However I am now making trying to have the site use more AJAX, to lessen the page reloads. In PHP I had a lovely object orientated user class with methods for updating data, logging out, and so on. When a user logs on this would be stored as a session variable, and then any page that wishes to do anything the user could just grab it from the session and call it's methods. Clearly this use of php objects and the session doesn't really work with ajax. However I don't want to have to scrap storing the user in an object (which neatens things up somewhat), so don't just want to go down the route of defining a ton of js functions that grab the current username, and use the to do mysql queries through ajax.  Am I being stupid here, and what route would people recommend I take.</p>

答:
Sessions and objects still work with ajax. Sessions persist information on the server-side and objects are just organization structures for the code that is executed there.  Much of what you are asking is stuff you pick up from experience programming in general.  You should do a little reading and planning to come up with a more solid blueprint of how you want the application to work.

First, check out resources like the following:

www [dot] phptherightway [dot] com

www [dot] codecademy [dot] com/tracks/javascript-combined

More specifically:

http://www.phptherightway.com/pages/Design-Patterns.html
https://en.wikipedia.org/wiki/Front_Controller_pattern

These are the fundamentals of code organization.  Learn them early and life will be easier down the road.  Once you have those down pat, you will likely know where to go to find more advanced solutions.  Of course, stackoverflow is a great resource to find all kinds of solutions.

Always keep in mind that with AJAX, you are doing the same request/response cycle you always do from the server-side perspective.  From the client side perspective, you are treating sections of the page as independent little browsers that are capable of making new requests while you are looking at the page.  So, with that in mind the following example would be a method of achieving what you are looking to do.

header file segment

```<code><script>
    jQuery(function(){
        jQuery('#login').click(function(e){
            //stops form from submitting via normal behavior
            e.preventDefault();
            //cache the form element because each time
            //you do a jQuery() search, a puppy dies
            var form = jQuery(this).parents('form');
            jQuery.post(
                form.attr('action'),
                form.serialize(),
                function(data) {
                   var responseString = 'Logged in as ' + data.firstName + ' ' + data.lastName;
                   form.html(responseString);
                }
            );
        });
    });
</script>
<form action="ajax_controller.php">
    <input type="hidden" name="action" value="authenticate" />
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="submit" />
</form>
</code>```

ajax controller

```<code><?php
    if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
        /* Safety first, but use the mysqli version of
         * this if you are using a mysql db
         */
        foreach ($_POST as $post)
            $_POST = mysql_real_escape_string($post);

        if ($_POST['action'] === 'authenticate') {
            $user = new User($_POST['username']);
            $success = $user->authenticate($_POST['password']);

            //let's pretend authenticate() returns true or error message
            if ($success === true) {
                $response = array(
                    'firstName' => $user->get_firstName(),
                    'lastname' => $user->get_lastName()
                );
                return json_encode($reponse);
            } else {
                return $success;
            }
        }
    } else {
        //bark and throw exception, or return html, or whatever
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Sessions and objects still work with ajax. Sessions persist information on the server-side and objects are just organization structures for the code that is executed there.  Much of what you are asking is stuff you pick up from experience programming in general.  You should do a little reading and planning to come up with a more solid blueprint of how you want the application to work.

First, check out resources like the following:

www [dot] phptherightway [dot] com

www [dot] codecademy [dot] com/tracks/javascript-combined

More specifically:

http://www.phptherightway.com/pages/Design-Patterns.html
https://en.wikipedia.org/wiki/Front_Controller_pattern

These are the fundamentals of code organization.  Learn them early and life will be easier down the road.  Once you have those down pat, you will likely know where to go to find more advanced solutions.  Of course, stackoverflow is a great resource to find all kinds of solutions.

Always keep in mind that with AJAX, you are doing the same request/response cycle you always do from the server-side perspective.  From the client side perspective, you are treating sections of the page as independent little browsers that are capable of making new requests while you are looking at the page.  So, with that in mind the following example would be a method of achieving what you are looking to do.

header file segment

<script>
    jQuery(function(){
        jQuery('#login').click(function(e){
            //stops form from submitting via normal behavior
            e.preventDefault();
            //cache the form element because each time
            //you do a jQuery() search, a puppy dies
            var form = jQuery(this).parents('form');
            jQuery.post(
                form.attr('action'),
                form.serialize(),
                function(data) {
                   var responseString = 'Logged in as ' + data.firstName + ' ' + data.lastName;
                   form.html(responseString);
                }
            );
        });
    });
</script>
<form action="ajax_controller.php">
    <input type="hidden" name="action" value="authenticate" />
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="submit" />
</form>

ajax controller

<?php
    if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
        /* Safety first, but use the mysqli version of
         * this if you are using a mysql db
         */
        foreach ($_POST as $post)
            $_POST = mysql_real_escape_string($post);

        if ($_POST['action'] === 'authenticate') {
            $user = new User($_POST['username']);
            $success = $user->authenticate($_POST['password']);

            //let's pretend authenticate() returns true or error message
            if ($success === true) {
                $response = array(
                    'firstName' => $user->get_firstName(),
                    'lastname' => $user->get_lastName()
                );
                return json_encode($reponse);
            } else {
                return $success;
            }
        }
    } else {
        //bark and throw exception, or return html, or whatever
    }


答:
Early and late binding only make sense in the context of types and not the way you are describing it. Pretty much all modern languages are typed in the sense that all values have fixed types. The difference comes in when we look at dynamically vs statically typed languages. In dynamically typed languages variables don't have types so they can refer to values of any type and this means that when you call a method on an object referred to by some variable the only way to determine whether that call is valid or not is to look up the class for the object and see if that method actually exists. This allows for some cool things like adding new methods to classes at run time because the actual method lookup is deferred up until the very last moment. Most people call this state of affairs late binding.

In a statically typed language variables have types and once declared can not refer to any value that is not of the same type. This isn't strictly true but lets assume it for now. Now if you know that the variable will only ever refer to values of a specific type then there is no reason to figure out if a method call is valid or not at run time because you can determine the validity before the code is ever run. This is referred to as early binding.

An example to demonstrate late binding in ruby:

```<code>a = 1 # a is an integer at this point
a.succ # asking for its successor is valid

class A
  def method_a
    # some code
  end
end

a = A.new
a.method_a # this is also valid
a.succ # this is not valid

class A # we can re-open the class and add a method
  def succ
    # some more code
  end
end
a.succ # now this is valid
</code>```

The above sequence of actions is not possible in a language like Java where all types are fixed at run time.

Title: What is early and late binding?

Body:
I keep hearing about early and late binding, but I do not understand what they are. I found the following explanation which I do not understand:

Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time.

Could someone please define the two types of binding and compare them?

Body:
Early and late binding only make sense in the context of types and not the way you are describing it. Pretty much all modern languages are typed in the sense that all values have fixed types. The difference comes in when we look at dynamically vs statically typed languages. In dynamically typed languages variables don't have types so they can refer to values of any type and this means that when you call a method on an object referred to by some variable the only way to determine whether that call is valid or not is to look up the class for the object and see if that method actually exists. This allows for some cool things like adding new methods to classes at run time because the actual method lookup is deferred up until the very last moment. Most people call this state of affairs late binding.

In a statically typed language variables have types and once declared can not refer to any value that is not of the same type. This isn't strictly true but lets assume it for now. Now if you know that the variable will only ever refer to values of a specific type then there is no reason to figure out if a method call is valid or not at run time because you can determine the validity before the code is ever run. This is referred to as early binding.

An example to demonstrate late binding in ruby:

a = 1 # a is an integer at this point
a.succ # asking for its successor is valid

class A
  def method_a
    # some code
  end
end

a = A.new
a.method_a # this is also valid
a.succ # this is not valid

class A # we can re-open the class and add a method
  def succ
    # some more code
  end
end
a.succ # now this is valid

The above sequence of actions is not possible in a language like Java where all types are fixed at run time.


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
IMHO: Peter Norvig already answered this question much better than anyone else:

Learn at least a half dozen
  programming languages. Include one
  language that supports class
  abstractions (like Java or C++), one
  that supports functional abstraction
  (like Lisp or ML), one that supports
  syntactic abstraction (like Lisp), one
  that supports declarative
  specifications (like Prolog or C++
  templates), one that supports
  coroutines (like Icon or Scheme), and
  one that supports parallelism (like
  Sisal).

ContentLicense: CC BY-SA 2.5


答:
Late binding is when behavior is evaluated at runtime. It's necessary when you indeed want to determine how to act based on information you only have when the program is running. The clearest example in my opinion is the virtual function mechanism, specifically in C++.

```<code>class A
{
public:
    void f() {}
    virtual void g() {}
};

class B : public A
{
    void f() {}
    virtual void g() {}
};

int main()
{
    A* a = new B;
    a->f();
    a->g();
}
</code>```

In this example,a->f() will actually call void A::f(), because it's early (or statically) bound, and so the program at runtime thinks it's just a pointer to an A type variable, whereas a->g() will actually call void B::g(), because the compiler, seeing g() is virtual, injects code to look up the address of the correct function to call at runtime.

Title: What is early and late binding?

Body:
Late binding is when behavior is evaluated at runtime. It's necessary when you indeed want to determine how to act based on information you only have when the program is running. The clearest example in my opinion is the virtual function mechanism, specifically in C++.

class A
{
public:
    void f() {}
    virtual void g() {}
};

class B : public A
{
    void f() {}
    virtual void g() {}
};

int main()
{
    A* a = new B;
    a->f();
    a->g();
}

In this example,a->f() will actually call void A::f(), because it's early (or statically) bound, and so the program at runtime thinks it's just a pointer to an A type variable, whereas a->g() will actually call void B::g(), because the compiler, seeing g() is virtual, injects code to look up the address of the correct function to call at runtime.


问:
Applying commits into another branch without merging
I have two git branches with almost the same code, but some minor changes in order to support different platforms.

I need to maintain these changes because I need them to run the software on different computers. So there is no master and development branch, both are equally important.

Nevertheless, I need to "synchronize" the core code base of the branches. So I would like to somehow apply the commits from one branch in a sort of patch fashion to the other branch and vice versa, without merging them, in order to maintain the different setups.

Is this possible with git?
If yes, how can I accomplish this?

Edit: can I merge only some files and leaves others out, but maintain the two branches?

答:
There are various ways to do this with git, as others have lined out - cherry-picking, introducing another branch, manually applying patches, etc.

I seems though that this is not what you really should do. You are managing a codebase that is to be deployed on different platforms; the different "versions" are not different development states of your code tree, but rather different products derived from it, a.k.a. builds.

So, set up a build system if you haven't already (can be as simple as a shell script running a few rsync or cp -r jobs). Make it so that you can pass it an argument that determines for which platform to build, and based on that argument, the build system decides which files to include in the release package. With just a bit of good structure, you spend a day or so getting the build scripts right, and then never worry about it again.


答:
There are two major concepts in confusion: binding and loading.  It is conflated by the concept of DataBinding, which is somewhere in the middle often doing both.  After considering it, I am going to add one more concept, to complete the trifecta, dispatch.

    Types

Late Binding: type is unknown until the variable is exercised during run-time; usually through assignment but there are other means to coerce a type; dynamically typed languages call this an underlying feature, but many statically typed languages have some method of achieving late binding

Implemented often using [special] dynamic types, introspection/reflection, flags and compiler options, or through virtual methods by borrowing and extending dynamic dispatch

Early Binding: type is known before the variable is exercised during run-time, usually through a static, declarative means

Implemented often using standard primitive types

    Functions

Static Dispatch: known, specific function or subroutine at compile time; it is unambiguous and matched by the signature

Implemented as static functions; no method can have the same signature

Dynamic Dispatch: not a specific function or subroutine at compile time; determined by the context during execution. There are two different approaches to "dynamic dispatch," distinguished by what contextual information is used to select the appropriate function implementation.

In single [dynamic] dispatch, only the type of the instance is used to determine the appropriate function implementation. In statically-typed languages, what this means in practice is that the instance type decides which method implementation is used irrespective of the reference type indicated when the variable is declared/assigned.  Because only a single type -- the type of the object instance -- is used to infer the appropriate implementation, this approach is called "single dispatch".

There is also multiple [dynamic] dispatch, where input parameter types also help determine which function implementation to call. Because multiple types -- both the type of the instance and the type(s) of the parameter(s) -- influence which method implementation is selected, this approach is dubbed "multiple dispatch".

Implemented as virtual or abstract functions; other clues include overridden, hidden, or shadowed methods.

NB:  Whether or not method overloading involves dynamic dispatch is language-specific.  For example, in Java, overloaded methods are statically dispatched.

    Values

Lazy Loading: object initialization strategy that defers value assignment until needed; allows an object to be in an essentially valid but knowingly incomplete state and waiting until the data is needed before loading it; often found particularly useful for loading large datasets or waiting on external resources

Implemented often by purposefully not loading a collection or list into a composite object during the constructor or initialization calls until some downstream caller asks to see the contents of that collection (eg. get_value_at, get_all_as, etc).  Variations include loading meta information about the collection (like size or keys), but omitting the actual data; also provides a mechanism to some runtimes to provide developers with a fairly safe and efficient singleton implementation scheme

Eager Loading: object initialization strategy that immediately performs all value assignments in order to have all the data needed to be complete before considering itself to be in a valid state.

Implemented often by providing a composite objects with all their known data as soon as possible, like during a constructor call or initialization

Data Binding: often involves creating an active link or map between two compatible information streams so that changes to one are reflected back into the other and vice versa; in order to be compatible they often have to have a common base type, or interface

Implemented often as an attempt to provide cleaner, consistent synchronization between different application aspects (eg view-model to view, model to controller, etc.) and talks about concepts like source and target, endpoints, bind/unbind, update, and events like on_bind, on_property_change, on_explicit, on_out_of_scope

EDIT NOTE: Last major edit to provide description of examples of how these often occur.  Particular code examples depend entirely on the implementation/runtime/platform

Title: What is early and late binding?


答:
Anything that is decided by compiler while compiling can be refer to EARLY/COMPILE TIME Binding and anything that is to be decided at RUNTIME is called LATE/RUNTIME binding.

For Example,

Method Overloading and Method Overriding.

1) In Method Overloading your method calls to the methods are decided by the compiler in the sense that which function is going to be called is decided by your compiler at compile time. Hence being EARLY BINDING.

2) In method Overriding, it is decided at RUNTIME which method is going to be called. So it is reffered as LATE BINDING.

Tried to keep it simple and easy to get. Hope this helps.

Title: What is early and late binding?


问:
Need help on user story with multiple condition
I have the following user story:

As a registered user i can request for a new license key

with the following condition

When the user request a license key they required to enter some
hardware id

Should i create another user story base on this condition? example

As a registered user i can request a new license key only when
hardware id is provided.

In a situation when i have multiple condition should i create many user story to fit in the condition?

thanks

答:
It actually depends on the story size (i.e. its complexity). If the team feels that implementing/testing each condition is a fairly independent activity with its own complexity, then you can go for different stories.

However, in most cases, the conditions are trivial - and hence can be accommodated as different acceptance criteria on the same user story.


问:
Writing Testable Code vs Avoiding Speculative Generality
I was reading some blog posts this morning, and stumbled across this one:

If the only class that ever implements the Customer interface is
  CustomerImpl, you don't really have polymorphism and substitutability
  because there is nothing in practice to substitute at runtime. It's
  fake generality.

That makes sense to me, as implementing an interface adds complexity and, if there is only ever one implementation, one might argue that it adds needless complexity.  Writing code that is more abstract than it needs to be is often considered to be code smell called "speculative generality" (also mentioned in the post).

But, if I'm following TDD, I can't (easily) create test doubles without that speculative generality, whether in the form of interface implementation or our other polymorphic option, making the class inheritable and its methods virtual.

So, how do we reconcile this tradeoff?  Is it worth it to be speculatively general to facilitate testing/TDD?  If you're using test doubles, do these count as second implementations and thus make the generality no longer speculative?  Should you consider a more heavyweight mocking framework that allows mocking of concrete collaborators (e.g. Moles versus Moq in the C# world)?  Or, should you test with the concrete classes and write what could be considered "integration" tests until such time as your design naturally requires polymorphism?

I'm curious to read other people's takes on this matter -- thanks in advance for your opinions.

答:
I have seen many advantages since I started programming more to an interface beyond polymorphism.

It forces me to think harder about the interface of the class (it's public methods) beforehand and how it will interact with other classes' interfaces.

It helps me write smaller classes that are more cohesive and follow the single responsibility principal.

It is easier to test my code

Less static classes / global state as the class must be instance-level

Easier to integrate and assembly pieces together before the whole program is ready

Dependency injection, separating object construction from the business logic

Many people will agree that more, smaller classes are better than fewer, bigger classes. You don't have to focus on as much at one time and each class has a well-defined purpose. Other's may say you are adding to the complexity by having more classes.

It is good to use tools to improve productivity, but I think relying solely on Mock frameworks and such in place of building testibility and modularity directly into the code will result in lower quality code in the long run.

All in all, I believe it has helped me write higher quality code and the benefits far outweigh any consequences.


答:
“is knowing .NET development
  environment enough for a successful
  carrier in IT industry”.

No.

You probably can have a career knowing only .NET, but this attitude is the antithesis of the attitude every single good or successful developer I have ever met has had.

Good developers are curious, good developers are always hungry to learn new ways of doing things, new technologies, new techniques. The accumulation of knowledge and knowhow is catnip to good developers.

Bad developers don't want to learn new stuff, keep within their comfort zone, put a box around the limits of what they are prepared to learn.

So the answer, again is no. Not because there is anything wrong with .NET (the answer would be the same whichever technology was mentioned) but because of the attitude inherent in the question.

Title: Is knowing .NET only enough for a successful career in IT industry?

Body:
Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.


答:
Instead of giving you an academic definition I will try to show you some of the differences using a real world example using VBA:

Early binding:

```<code>Dim x As FileSystemObject
Set x = New FileSystemObject
Debug.Print x.GetSpecialFolder(0)
</code>```

This requires a reference to be set to the "Microsoft Scripting Runtime" component at design time. It has the advantage that you get an error message already at compile time when you have a typo in FileSystemObject or method names like GetSpecialFolder.

Late binding

```<code>Dim x As Object
Set x = CreateObject("Scripting.FileSystemObject")
Debug.Print x.GetSpecialFolder(0)
</code>```

This does not require a reference to be set beforehand, the instance creation and type determination will just happen at run-time. The compiler won't complain at compile-time when you try to call a non-existent method of x, this will lead to a run-time error only when the specific line is executed.

So, the disadvantage of late binding is that you don't have any strong type checking here. But that is also the advantage - let's say you have a component where several versions exist, and each newer version provides some additional functions. (A real-world example are the MS Office components, like the Excel COM interface)  Late binding allows you write code which works together with all of that versions - you can first determine the specific component version, and if you find out that you have only an older version available, avoid to execute functions calls which don't work with that version.

Title: What is early and late binding?

Body:
Instead of giving you an academic definition I will try to show you some of the differences using a real world example using VBA:

Early binding:

Dim x As FileSystemObject
Set x = New FileSystemObject
Debug.Print x.GetSpecialFolder(0)

This requires a reference to be set to the "Microsoft Scripting Runtime" component at design time. It has the advantage that you get an error message already at compile time when you have a typo in FileSystemObject or method names like GetSpecialFolder.

Late binding

Dim x As Object
Set x = CreateObject("Scripting.FileSystemObject")
Debug.Print x.GetSpecialFolder(0)

This does not require a reference to be set beforehand, the instance creation and type determination will just happen at run-time. The compiler won't complain at compile-time when you try to call a non-existent method of x, this will lead to a run-time error only when the specific line is executed.

So, the disadvantage of late binding is that you don't have any strong type checking here. But that is also the advantage - let's say you have a component where several versions exist, and each newer version provides some additional functions. (A real-world example are the MS Office components, like the Excel COM interface)  Late binding allows you write code which works together with all of that versions - you can first determine the specific component version, and if you find out that you have only an older version available, avoid to execute functions calls which don't work with that version.


问:
Uses of WCF Binding
From MSDN, we have the following definition of WCF Binding

Bindings specify how a WCF service endpoint communicates with other endpoints.

At its most basic, a binding must specify the transport (for example, HTTP or TCP) to use. You can also set other characteristics, such as security and transaction support, through bindings.

I am looking for practical uses of WCF. The scnearions in which people tweak the abilities of WCF Binding. Some of them are listed below.

Exporting Metadata: -  Custom policy assertions are exported by implementing the IPolicyExportExtension interface on a BindingElement class.

What are the other practical uses of Binding that you usually use?

答:
Bindings are useful when you want to expose the same end-point over different protocols - such as http or tcp. Also, you can have separate bindings in case you want to use the WS-* standards (for transactions/security capabilities) via the 'wsHttpBinding' pre-defined binding.

Sometimes, developers tweak the finer attributes on a binding. A good example is using 'streamedMode' of data transfer when large messages are involved. This eliminates the need of large memory buffers.

Title: Uses of WCF Binding


答:
Are there different ways of asking for requesting a license key? Can you deliver them individually whilst generating value for the customer?

If so, they are possibly multiple stories. If not, they are definitely not separate stories.

Stories need to be independent, negotiable, valuable, estimable, small and testable (INVEST). So make them as small and independent as possible, while keeping them valuable.

Title: Need help on user story with multiple condition

Body:
I have the following user story:

As a registered user i can request for a new license key

with the following condition

When the user request a license key they required to enter some
hardware id

Should i create another user story base on this condition? example

As a registered user i can request a new license key only when
hardware id is provided.

In a situation when i have multiple condition should i create many user story to fit in the condition?

thanks


问:
Is user story the best form of requirement in agile project?
Statistically speaking, user story maybe the most popular requirement technique in Agile but I am curious to know the alternatives and why.</p>

答:
A back log of user stories happens to be a good way to facilitate the communication of requirements. But agile wouldn't be agile, if you weren't allowed to come up with an alternative approach. Just remember the following:

Embrace Change

The only way to avoid waste, and be ready for priority changes late into your project, is to group your requirements into 'chunks'. Preferably, each chunk by itself adds some value to the product. And these chunks should be small enough, so that they can be completed in a short time. That creates many opportunities in your project to change the requirements. If you call these chunks 'user stories', or something else... that's not so important.

People over Processes

Agile is also about human interaction. So instead of writing a lot of requirements and handing over a massive document, agile encourages you to use human dialog. So its okay if the requirements are not too detailed at first, and then more thoroughly discussed with the team shortly before implementation. (You might want to keep a digital record of the outcome of these discussions though).

Planning and Reporting

By doing the detailed requirements as late as possible, you also avoid wasted time in requirement gathering.

Then, why even bother writing something like user stories in advance? Well, you need at least some 'hook' for future requirements, to be able to do planning, and predict the future (eg. a release date) based on factual data from the past.

User Stories

Looking back at these requirements, users stories are not so bad: They are a light-weight (single-sentence) representation of a chunk of requirements (the details to be discussed later). Allowing you to plan ahead and visualize your strategy (eg. a back log). With minimal waste.


问:
Violation of the C definition?
The C standard states that any character in the machine's standard printing set will never be negative.But the following code:

```<code>char c=1234;
printf("%d\t%c",c,c);
</code>```

gives a negative output and prints a strange character,meaning that the character is in machine's printing character set.Is the C standard being violated here?

答:
Well, I am not an expert on this, but the key is what the C standard means by "machine's standard printing set". On most modern machines/systems this will be 7-bit ASCII. So as long as you assign just characters of that range to a char variable, you can be sure that, when interpreted as an integer, you get a positive value.

The (full) printing set of a machine may contain a lot more characters, but when you, for example, assign an umlaut like ä, ö or ü to a character variable, you have to expect on some machines the integer conversion of that variable becoming <0, on others >0, this is not defined in the standard. Furthermore, there is no guarantee that such a character will always be printed as the same letter, this may, for example, depend on the activate codepage or the environment of the program.

Title: Violation of the C definition?


答:
The part of the C standard (link is to a late draft of C11) you're interested in is section 6.3.1.3 (page 69 of the PDF), which says:

6.3  Conversions

6.3.1.3 Signed and unsigned integers

1 When a value with integer type is converted to another integer type
  other than _Bool, if the value can be represented by the new type, it
  is unchanged.

2 Otherwise, if the new type is unsigned, the value is converted by
  repeatedly adding or subtracting one more than the maximum value that
  can be represented in the new type until the value is in the range of
  the new type.

3 Otherwise, the new type is signed and the value cannot
  be represented in it; either the result is implementation-deﬁned or an
  implementation-deﬁned signal is raised.

Your first statement requires the conversion of an int (signed or unsigned, doesn't matter in this case) to a signed char.  Because the new type is signed and can't represent 1234, the behavior described in item 3 is triggered.

Indeed,  if you have warnings enabled on when you compile the code, you should get an error like this one from gcc:

junk.c:4: warning: overflow in implicit constant conversion

Title: Violation of the C definition?

Body:
The C standard states that any character in the machine's standard printing set will never be negative.But the following code:

```<code>char c=1234;
printf("%d\t%c",c,c);
</code>```

gives a negative output and prints a strange character,meaning that the character is in machine's printing character set.Is the C standard being violated here?


问:
How to handle conflicts between developers in your team?
This is happening in every team.

For some reasons, conflicts arise in the team and they affect the overall motivation and productivity.

What is your recommended approach to solve that common problem?

Examples:

one part of the team wants to implement dependency injection, the other part think it's a waste of time.

some developers think the rest of the team is slowing down development (which explains why they are late on the schedule)

personal incompatibilities between one or more developers

one developer refuse to talk to another one (without apparent reason)

答:
In my experience most conflicts of this nature come down to personality clashes.  Some of them have other elements but most commonly these are just being used as a vehicle for disagreement so even if you resolve the issue that they're arguing about, it's just a matter of time before something else comes up.

My advice:

1) The first thing is to make it clear to both of them that conflicts reflect badly on both of them and that there isn't going to be a winner and a loser, just two losers of varying degrees.

2) Make it clear to them that whatever happens you expect both of them to act in a professional manner.  They don't need to like each other but they do have to be civil, efficient and organised.  Make sure that it's reflected in their annual appraisals and reviews - inability to get on with a team mate is a significant issue with their performance.

3) Do listen to their issues with one another and where appropriate be sympathetic but also point out their failings in this area and avoid getting drawn into extended discussions or some judgement about who is right and who is wrong.  As I said above in 95% of cases (the remaining 5% being genuine bullying or the like which needs to be properly addressed as a disciplinary matter), they've both wrong and they need to understand that.

4) Where possible do keep them apart where it's easy to do so.  I don't generally find that throwing people together does anything more than stir it up.  If they're going to "reconcile" it will happen anyway and I suspect is more likely to happen when they're not continually in each others faces.


问:
Sorting and averaging the highest values of pixel data
Currently, I am using Android/Java.  I am looking for the most efficient means to determine the average of the highest 100 pixel values taken from a greyscale preview.

The preview part I am more or less okay with; however, it determining which sorting methodology is the most efficient.  The other option is to apply a threshold, which will eliminate most of the data.

Which sorting algorithm would be most efficient for an unsorted data set of over 3 million values?

答:
Are you looking for the average value of all pixels whose value is greater than 155 (or some other arbitrary threshold?) There's no need to do a sort.

Pseudo code:

```<code>integer sum
integer count

for each pixel
   if pixel value greater than threshold
      sum = sum + pixel value
      count++
   end if
end for

float average = sum / count
</code>```

Body:
Are you looking for the average value of all pixels whose value is greater than 155 (or some other arbitrary threshold?) There's no need to do a sort.

Pseudo code:

integer sum
integer count

for each pixel
   if pixel value greater than threshold
      sum = sum + pixel value
      count++
   end if
end for

float average = sum / count


问:
Redmine (or Trac) integration with customer issue-tracking system
I'm working in a software development area in my university, and we've noticed we need some system to track errors and bugs, who and when it is dealt with. I've researched some software management/bug tracking applications, with Redmine being the one that appeals to me the most because of its simple UI (actually I discovered that our server has one system, Trac, already installed, but it has never been used at its time and my colleagues told me it would take the same time to use any).

However, a colleague told me also that he has the idea of implementing a customer issue-tracking system in the medium/long term (he told me about creating tickets for users' problem, search into a knowledge base of common problems, and mark frequent problems to deal with them. It seems that things like OTRS are close to what he was thinking about. He's also researching about ITIL).

As far as I know, the developer issue-tracking system and the client problem-tracking system are different, and they must have some kind of integration between them. Or aren't they?  In case it does, my question is:

Is it possible to integrate Redmine (or Trac, if it's easier, or in general a project management/bug-tracking system) with this kind of customer issue-tracking systems? Do I have to worry about changing my project management system in the future to implement that? Or is the implementation easier with some of them?

答:
Ultimately there is never any integration between these things. They aren't designed to work with "some other" tracker. Or if they have an API, no-one uses it to integrate it with anything unless you're in a large enterprise shop, and then integration will end up being with something like Sharepoint (sigh).

The best thing you can do in such cases is to add a custom field to every internal bug item that contains a reference to your external bug tracker. It's a manual process and prone to error, but it's the only realistic way you can tie the two together. The rest of the time, you simply use them separately - no data gets exchanged between them.

If you can use the same one, then do so, but I know many places cannot do this and there's always a disconnect between the support teams tracker and the dev teams tracker.


问:
Looking for meaningful, strong argument in favor of antivirus software on development machines
When forming opinions, it is a good practice to follow scholastic tradition - think as hard as you can against the opinion you hold and try to find counter-arguments.

However, no matter how hard I try, I just cannot find reasonable arguments in favor of antivirus (and related security measures) on development machines.

Arguments against antivirus(AV) in development are plentiful:

It is not uncommon for 1 minute build to take 10 times longer with AV on

In a conference talk, IntelliJ developers claim AV software is #1 suspect when their IDE is sluggish

Unzipping comes with roughly 100 kb/s speed with AV on

AV renders Cygwin completely unusable (vim takes 1 minute to open a simple file)

AV blocks me from downloading useful files (JARs, DLLs) from colleagues' e-mails

I can't use multiple computers for development, since AV / security measures prevent me from unblocking ports

AV kills performance of programs with high file turnover, such as Maven or Ant

Last, but not least - what does AV actually protect me from? I am not aware of my AV program ever stopping any security thread.

If the reason is fear of disclosing NDA stuff - no AV can possibly prevent me from doing it if I set my mind to it.

If the reason is fear of losing source code and/or documentation - there are distributed revision systems for this (there are at least 20 copies of our repo and we sync on daily basis).

If the reason if fear of disclosing customer data - developers rarely work connected to real production databases, instead they are playing around in toy environments.

Even if there are meaningful arguments in favor of having AV on development machines, they fall apart when faced with the ability to run a Virtual Machine in your paranoidly protected environment.

Since I want to keep an open mind of the issue, could anyone present meaningful, strong argument in favor of Anti-virus software for developers?

答:
As soon as there exists AV software for power users, I'd say there would be no reason against it. The problem is that all* AV software is made for your parents. They have more money than you, and are willing to pay for the feeling of security (and clicking more buttons to download kitten toolbars).

* For suitable values of "all." I've found every AV program so far (about half a dozen major brands) extremely obnoxious and invasive.


答:
Story:

```<code>As a [registered user],
I want to [request a new license key for my new hardware]
So that [I can use the product on my new hardware]
</code>```

Test Scenario:

```<code>Given: a registered user and the new hardware information
When: a new license key is requested
Then: verify the user registration AND the hardware information AND issue the new key
</code>```

Body:
Story:

As a [registered user],
I want to [request a new license key for my new hardware]
So that [I can use the product on my new hardware]

Test Scenario:

Given: a registered user and the new hardware information
When: a new license key is requested
Then: verify the user registration AND the hardware information AND issue the new key


问:
Giving a double type for sqrt library function in C
The C Programming Language by Ritchie says that:

The library routine sqrt expects a double type and will produce nonsense if inadvertently handled something else. So if n is an integer, we can use sqrt((double) n) to convert the value of n to double.

But the following code works fine on my system:

```<code>printf("%f",sqrt(9));
</code>```

Then also it is giving the same result as sqrt((double)9). Why is my compiler not following the book?

答:
because of implicit conversion, new compilers will upgrade some types to fit the target type,

int to double is one of the legal conversions


答:
It depends on whether you've declared the function prototype, double sqrt(double); .  (The usual way of doing so is with #include <math.h>.

If you have, then C will implicitly convert the function parameter to the correct type.  If not, the compiler will accept your code anyway, but the 9 will be incorrectly passed as an int instead of being converted to a double.

However, there are some compilers that treat sqrt as an intrinsic function, and “know” that its parameter is a double even if you don't declare it.

Title: Giving a double type for sqrt library function in C

Body:
The C Programming Language by Ritchie says that:

The library routine sqrt expects a double type and will produce nonsense if inadvertently handled something else. So if n is an integer, we can use sqrt((double) n) to convert the value of n to double.

But the following code works fine on my system:

```<code>printf("%f",sqrt(9));
</code>```

Then also it is giving the same result as sqrt((double)9). Why is my compiler not following the book?


问:
Adding new objects to a clientside array - best practices?
Say you have a list of "vehicles" - you have an observableArray of these ko.observable()s.

You let your user add a new vehicle with the following:

```<code>var emptyVehicle = {
    "make": "chevrolet",
    "model": "corvette"
};
app.on('CLICKED_ADD_VEHICLE', function () {
            var vehicle = new vehicleViewModel(emptyVehicle);
            vehicle.hasWheels(true);
            innerModel.sets.push(set);
        });
</code>```

If they save the vehicle, you get a real vehicle from your dataservice, and then replace the blank one with this:

```<code>app.on('CLICKED_SAVE', function (oldVehicle) {
            var newVehicle = new vehicleViewModel(dataservice.createVehicle(oldVehicle));
                    innerModel.vehicles.remove(oldVehicle);
                    innerModel.vehicles.push(newVehicle);
        });
</code>```

I know I'm leaving some code out here, but this is more of a practices/approach question than a code question.  Is this an acceptable approach to adding new items to a list?  New up a temporary template, and throw it away in place of an actual item if the user saves?

答:
It's acceptable, but it's not really preferred.  What happens if someone changes the code latter on, and it fails to send oldVehicle?  What happens if the CLICKED_SAVE event is triggered again?  What happens if the AJAZ call itself just fails?

Better practice is to design your app to begin with an empty innerModel.vehicles array, and then have addVehicle be a method of app that spools up a new vechicleViewModel and pushes it to the array.

Generally, events should call methods, even if they aren't UI events, unless you have a good reason not to.


问:
Implementation defined behaviour changing const type in c
The C standard states that if an attempt is made to change a const type,the result is implementation defined.This gives error on my system,but what does it depend on(compiler,os)?
What are the possible results(implementation defined) on various machines?</p>

答:
You seems to have misunderstood the C standard. Trying to modify a const-qualified variable is a constraint violation and must therefore result in a diagnostic message from the compiler.

If you try to subvert that mechanism (for example, by casting away the const), then you are on your own. Trying to modify an object that was defined as const results in Undefined Behaviour, which means that literally anything is possible. There is no implementation-defined behaviour within the context of const in the C standard.


问:
I'm trying to figure out which functions from one C library are being used by C project. Does anyone have a simple solution?
To be specific, I want to know which function/types in libpri and being used in the Asterisk project. I'm not traditionally a C programmer, but I know some basic stuff because I took a class in college.</p>

答: Assuming that your code compiles... comment out the line that imports the library in question (i.e. comment out the line that imports libpri). Then try to compile the code. The functions that the compiler says it can't find/identify are the ones being used from the library.</p>


问:
Is "send us a page with code" a typical interview requirement?
Recently I was asked to show "a page with code" for a job interview. Being mainly a back-end programmer, and that's the position I applied for, I first said to the person I was talking to exactly that: PHP is executed at the server and therefore not visible by just giving a "page".

However, following their desire, I sent links to the pages I've worked on before. Obviously they couldn't see anything except for the HTML, CSS, JS... They said it was not enough, they could not see the PHP.

Understanding that they probably just wanted to know my skills and/or interest I sent them my Stack Overflow profile. Among all my questions and answers, most of them with code, certainly the PHP is there. But it seems this is not what they wanted.

Well, I don't have any code put together that I can simply publish for someone to see. And I would never do it for the code I have deployed, obviously.

So my question is/are: What does "send us a page with code" mean? What should I send? Is this a typical interview requirement?

答:
Asking to send code -- I dunno.
Using previously written code in interview is IMO fair game. On interview I always have a pen drive in my pocket with my previous work, and happy to show it if there is an interest. (And there is no interest O,O.  Droid interviewer sticks to make me reimplement strstr() or strcat() rather than accepting to look my solution for real world problems...)

As interviewer I'd be more than happy with such offer. I would not ask to send code as it is useless without context and explanation. code review works best if done face to face. ;-)


答: if you statically import the library you can remove the lib reference from the linker and see which symbols are undefined</p>

Title: I'm trying to figure out which functions from one C library are being used by C project. Does anyone have a simple solution?

Body: To be specific, I want to know which function/types in libpri and being used in the Asterisk project. I'm not traditionally a C programmer, but I know some basic stuff because I took a class in college.</p>


问:
Copyright notices: What if I change my surname? What if someone else has the exact same name?
I'm adding copyright notices to all my source code files:

```<code>Copyright (C) 2013 My-First-Name My-Surname
</code>```

But what if someone else is also named My-First-Name My-Surname? What does courts think about that? How would they know who is the real author? Is there something I can/should do about this situation? (So they'd know for sure)

What if I change my surname. Then, how do other people know that I'm still the copyright holder? Is there something I can/should do, to avoid trouble with copyright, after I've changed my name?

An example of when the above could be of interest: Someone gets married and change his/her surname and moves to a new address. Then, even if s/he has submitted his/her source code to the U.S. Copyright Office, that was done using his/her old name and address. Now s/he however has a new name and address. But there is perhaps other people that have the old name (but not also the old address). (In my country, for any first + middle + surname, there are usually many people with that full name.)

Apparently people think this is a weird question, but I've read about rather many very decisions made in courts, e.g. someone suing for hot coffee and winning millions of dollars.

答:
Copyright notices are optional in any country that is part of the Berne Convention (e.g., the USA).  You have a copyright in everything you write, even if you don't include a notice.  Adding a notice increases the legal risk to someone who violates your copyright.  If you really want to hit them with a big stick, you don't just include a notice, but also register your copyright (in the USA, with the US Copyright Office), then any damages you get to claim increase significantly.

The whole point is to put others on notice that you own the code.  It is not to establish your ownership.


问:
Should a software company have a dedicated team for research and/or utility libraries?
I work in a company that does web applications for various banks and some smaller e-shops
We employ about 20 developers and have 4-5 projects in development at any one time.
Our development teams don't interact much and a lot of the same problems are done in varied ways(good to bad).

I was wondering if it would be a good idea for a company to have a team of programmers that do research on current frameworks and continually improve a common library of functions and a common framework to build current and future projects much faster and more efficiently.

How large should a team like this be?

Also should it have permanent members that train others or should it rotate people?

Update: I was thinking about a common project that people can work on for fun that might spark some interest. It seems that when people have job pressures the solutions they come up with are not the best.

答:
One important point is that it's impossible to develop a good framework in total isolation. Good frameworks are organically grown: when a programmer notices that he needs some specific functionality, he adds it to the framework, and so the framework grows little by little - as opposed to architecting a "perfect framework" up front, which never works, because the architect can't be aware of all eventually turning up use cases.

Of course, organically growing the framework has the downside that its internal integrity might not be too good, and it turns into spaghetti. If your team keeps up good internal communication, then you might be able to combine the best of both worlds: a separate architect team keeping up the integrity of the framework, but building for real needs of the end users (developers).


问:
Object design where hard-coded values are used to instantiate objects?
I'm creating the design for a browser bookmark merging program and I've ran into a design problem that I've seen before yet I've never come up with a good solution for it.  So lets say I have a Browser class:

```<code>Browser:
  String bookmarkFilePath
  String type
  Bool bookmarkFileExists()
</code>```

When my program runs I will want to have hard-coded values of common browsers and the locations of their Bookmarks file:

```<code>Object with hard-coded values:
  "~/Library/Application Support/Google/Default/Bookmarks", "Chrome"
  "~/Library/Safari/Bookmarks.plist", "Safari"
</code>```

Is there a design pattern or object type that could effectively take an object with hard-coded values (Browser name / bookmarks file path) and uses it to instantiate (and possibly manage) other (Browser) objects?

Also, flexibility is important since there are edge cases such as Firefox's file path to the bookmarks file is always different and some searching needs to be done.

EDIT: I will be implementing this in Python.  Sorry for not mentioning this before.

答: I would start with an enum with values like safari, chrome, opera ... and a constructor that takes a default path and maybe add methods to handle edge cases.</p>


问:
Anything beneficial from ORM for a NodeJS project already plain-SQL-implemented?
Well, actually it's a assignment project and I've already implemented a simple yet functional forum with NodeJS. But now we've been required to use ORM frameworks to refactor part of your code worth refactoring.

As I use Node.JS, there's no such type-safe benefits from ORM I could get. Besides, the code is already functional and I just don't see what good ORM could bring to it...

(Requests are handled pretty swiftly and independently... I don't think I would like to cache tons of Objects from database to request.session...)

My question is, what possible benefits will an ORM bring to a stable NodeJS project?

答:
ORMs provide a few benefits besides the primary purpose of mapping object data to relational data.  A traditional ORM and common 3rd party ORMs may not particularly fit what you are doing, and that is a good starting point for a rationale for explaining why one was not employed, but there are other benefits of ORMs that might want to consider or reconsider.

ORMS promotes or enforces the sharing of common interfaces at a distinct layer and system boundary

When encountering ORM specific types, one should be very close to leaving the realm of application code, and entering persistence code.  This should be the case even in the event that you roll up and put in place your own custom ORM over or in preference to a 3rd party's ORM.  Ideally, the structure of an application should be that dropping and replacing one ORM and an entire persistence mechanism with a competing or alternative ORM and persistence mechanism without a relative great deal of effort in the form of fundamental change should be relatively painless.

Some applications go to the trouble of making component replacement a particularly high priority and employ dependency injection to provide the actual ORM provider.  In this case, a purely academic setting, DI for the ORM provider is probably not necessary.  In fact, most projects would see that is quite beyond unnecessary.  For some though, that indirection and flexibility are very valuable as it allows different bits to be plugged in that provide notable situational benefits depending on which benchmarks or features they are chasing.  Forum software is one such class of software that might be a good candidate for that kind of flexibility, especially if targeted as a mass-market product.

Is there a clear distinction between domain behavior and persistency concerns?  Does that distinction occur in the same way across the entire or majority of the application?

Are queries first class citizens, or are they merely presented as formatted strings to a data source?  What kind of mechanism is in place to extend or modify a query?  Can queries be extended or modified through parameter assignment?  How are constraints managed?  Can the sorting strategy be easily changed programmatically during run-time?  Do not answer those questions here, just consider them as you further evaluate what it might mean to use an ORM or to employ the more prominent if understated features of an ORM.

Are there any behaviors within the persistence layer that are fundamentally the same and could benefit from further common abstractions?

ORMs often provide caching

Why do we use caching?  To keep needed frequently read, but infrequently written data, closer.  The only way to know definitively if caching would or would not help is through testing and profiling.  However, there are times where it just becomes obvious that some caching might help.

For instance, promoting a transient variable from a local block scope to a more global scope can be considered a form of caching and can significantly improve performance in the right circumstances.  That strategy, not unlike any other strategy has a tradeoff.  The tradeoff for promoting a variable's scope is we remove some inherent protections that come with that shorter lifetime and reduce the degree of encapsulation.

Forum software as a class of software is often a phenomenal candidate for caching.  Usually the bulk of forum operations is reading data many more often than writing data, especially considering the many forums have popular topics that are read and reread perhaps many times relative to the number of times new posts that extend the topic are added.  The forum software in question may not realize a great benefit as a purely academic project because it may not experience near real world conditions that real world scenarios of many users hammering away at the site would produce.

Since at this point you are not relying on a third party ORM, your potential caching mechanism and strategy is a bit more flexible.  You can use a common provider to cache both post-processed pages and datasets.

There are more benefits to ORMs that aren't mentioned.  But as this is academic, I don't want to take all the pleasure out of the research process.  Take a closer look what ORMs provide either as a direct, advertised benefit, or as a beneficial consequence or side-effect that often accompanies their use.


问:
Examples of UNIX Domain Socket Usage
Can anyone give an example of instances in which the AF_UNIX i.e unix domain sockets are used for process communication in a unix-based system</p>

答: socketpair is great to communicate with a child process. With SEQ_PACKET mode you need to do very little framework, just work on the meat.

Title: Examples of UNIX Domain Socket Usage


问:
Radix exchange sort implementation?
I need a little help understanding the implementation of radix exchange sort algorithm.

Radix exchange (I don't know if it's the exact name in english based literature) is a lot similar to quicksort, but uses binary representation of numbers.

Firts we look the highest digit in binary representation, and then using two indexes (from the beginning of the array and from the end, we increment the first if the given digit is 0, and decrement the other if the given digit is 1). Then we swap two numbers, and then continue the work until i = j (the indexes are equal). Then we have two separate partitions and sort them using the second most important digit and so on...

Mainly, I have a few questions:

Is this algorithm really called radix exchange or does it have some other, more commonly used name?

What are the advantages of this algorithm? It seems like a lot of work, and not very effective?

Where can I see an example of implementation of the algorithm? Maybe it will be a little more clearer on what it really is, because it's really confusing for me at the moment.

答:
it sounds like the time complexity would be O(n*k) and space complexity is O(k) with k being the number of bits of each element

in C++ it would be

```<code>radixQsort(int* arrb, int* arre, int rad=INT_BITS){
    if(arrb==arre)return;

    int* arrm = std::partition(arrb,arre,[rad](a){return !(a&(1<<rad));});

    radixQsort(arrb,arrm,rad-1);
    radixQsort(arrm,arre,rad-1);
}
</code>```

this is implemented using the partition in the standard library which works like the partition you described

Title: Radix exchange sort implementation?

Body:
it sounds like the time complexity would be O(n*k) and space complexity is O(k) with k being the number of bits of each element

in C++ it would be

radixQsort(int* arrb, int* arre, int rad=INT_BITS){
    if(arrb==arre)return;

    int* arrm = std::partition(arrb,arre,[rad](a){return !(a&(1<<rad));});

    radixQsort(arrb,arrm,rad-1);
    radixQsort(arrm,arre,rad-1);
}

this is implemented using the partition in the standard library which works like the partition you described


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
First things - timescale.  .NET isn't going to last you 40 years but you'll find that it will relatively naturally segway into something else as it dies so I'll assume you mean "is knowing .NET enough while .NET is around".

It depends how you define successful.

If you mean will you make plenty of money, get to do some interesting work and work at some OK companies with decent people then yes.  MS technologies tend to "cluster" in that companies will often use a full MS platform so .NET alone will cover a massive chunk of their needs and you can make a career out of it and many people will.  In addition whatever you may read about the decline of MS they're still very much alive and not going anywhere fast so there are going to be plenty of opportunities for the foreseeable future.

However you will probably find that you'd benefit as a programmer from seeing a bit more than just the way MS do things and that it might give you deeper understanding of what you're doing, even if you do decide to bring that experience back to working as a .NET developer.

So can you be successful - yes.  Could you potentially be more successful and maybe happier if you saw what else was out there - again, yes.


问:
Is this a viable approach to resolving multiple matches in a lexer?
I'm writing a lexer in JavaScript. It's pretty typical - rules are specified with regular expressions and produce a token.

I am unsure of the best way to handle when multiple rules are matched. The existing lexers I've looked at handle this by picking the rule with the longest match.

It also seems like a viable strategy, however, to simply use the first rule that matches. This is my current strategy.

Here is an example:

Input:

:=

Rules:

```<code>: -> COLON
= -> EQUALS
:= -> ASSIGN
</code>```

The longest-match rule would return ASSIGN, where the first-match rule would return COLON and then EQUALS.

Obviously this is not desirable, so under my implementation I would just reorder the rules to put the ASSIGN rule first as follows:

```<code>:= -> ASSIGN
: -> COLON
= -> EQUALS
</code>```

Is this a viable approach to just use the first matching rule? What are the advantages and disadvantages of each approach?

答: I wouldn't view it as "first" match, but having the lexer have defined priorities is not uncommon. The advantage of parsing colon first is on a miss, it eliminates two paths. If you miss assignment, you still need to check colon.</p>


答:
Put the hard-coded strings into a configuration file, fx using the INI format. That way you can exchange them without touching code.

paths.ini

```<code>Chrome="~/Library/Application Support/Google/Default/Bookmarks"
Safari="~/Library/Safari/Bookmarks.plist"
</code>```

or

chrome.ini

```<code>path="~/Library/Application Support/Google/Default/Bookmarks"
</code>```

safari.ini

```<code>path="~/Library/Safari/Bookmarks.plist"
</code>```

The first variant is better, if you use a factory for the browser objects, the second, if the browser object reads the configuration itself.

Title: Object design where hard-coded values are used to instantiate objects?

Body:
I'm creating the design for a browser bookmark merging program and I've ran into a design problem that I've seen before yet I've never come up with a good solution for it.  So lets say I have a Browser class:

```<code>Browser:
  String bookmarkFilePath
  String type
  Bool bookmarkFileExists()
</code>```

When my program runs I will want to have hard-coded values of common browsers and the locations of their Bookmarks file:

```<code>Object with hard-coded values:
  "~/Library/Application Support/Google/Default/Bookmarks", "Chrome"
  "~/Library/Safari/Bookmarks.plist", "Safari"
</code>```

Is there a design pattern or object type that could effectively take an object with hard-coded values (Browser name / bookmarks file path) and uses it to instantiate (and possibly manage) other (Browser) objects?

Also, flexibility is important since there are edge cases such as Firefox's file path to the bookmarks file is always different and some searching needs to be done.

EDIT: I will be implementing this in Python.  Sorry for not mentioning this before.

Body:
Put the hard-coded strings into a configuration file, fx using the INI format. That way you can exchange them without touching code.

paths.ini

Chrome="~/Library/Application Support/Google/Default/Bookmarks"
Safari="~/Library/Safari/Bookmarks.plist"

or

chrome.ini

path="~/Library/Application Support/Google/Default/Bookmarks"

safari.ini

path="~/Library/Safari/Bookmarks.plist"

The first variant is better, if you use a factory for the browser objects, the second, if the browser object reads the configuration itself.


答:
I'm reminded of the classic joke with the punchline "I wouldn't start from here.".

Since there is different behaviour associated with each specific browser, it seems to me that you actually have a number of different subclasses of the Browser base class:

The key difference between the subclasses being the differences in behaviour, not the difference in information structure.

Subclassing for differences in operation is less common than subclassing for differences in information, but it's still valid.

Given these classes, you could register each of them with an IoC container:

```<code>Bind<Browser>().To<Chrome>().InTransientScope();
Bind<Browser>().To<Safari>().InTransientScope();
Bind<Browser>().To<Firefox>().InTransientScope();
Bind<Browser>().To<Opera>().InTransientScope();
Bind<Browser>().To<InternetExplorer>().InTransientScope();
</code>```

(Syntax from NInject, but just typed in off the top of my head. Your IoC container of choice will differ.)

Then, you could define your main BookmarkMerger with this constructor:

```<code>public BookmarkMerger(IList<Browser> browsers) { ... }
</code>```

and rely on the IoC container to give you all the defined implementations, as object instances, ready to go.

If you still needed the folders to be soft-coded in a configuration file, instead of hard-coded in your source, each subclass could load it's own configuration when instantiated.

Body:
I'm reminded of the classic joke with the punchline "I wouldn't start from here.".

Since there is different behaviour associated with each specific browser, it seems to me that you actually have a number of different subclasses of the Browser base class:

The key difference between the subclasses being the differences in behaviour, not the difference in information structure.

Subclassing for differences in operation is less common than subclassing for differences in information, but it's still valid.

Given these classes, you could register each of them with an IoC container:

Bind<Browser>().To<Chrome>().InTransientScope();
Bind<Browser>().To<Safari>().InTransientScope();
Bind<Browser>().To<Firefox>().InTransientScope();
Bind<Browser>().To<Opera>().InTransientScope();
Bind<Browser>().To<InternetExplorer>().InTransientScope();

(Syntax from NInject, but just typed in off the top of my head. Your IoC container of choice will differ.)

Then, you could define your main BookmarkMerger with this constructor:

public BookmarkMerger(IList<Browser> browsers) { ... }

and rely on the IoC container to give you all the defined implementations, as object instances, ready to go.

If you still needed the folders to be soft-coded in a configuration file, instead of hard-coded in your source, each subclass could load it's own configuration when instantiated.


问:
Will I need to use AJAX for this?
Say I have a model written in php whose properties are the columns of a table in a db and each instance of the model represents a row in the table. I also have a page ('view') where I display the contents of each column one row at a time, starting with the first row (id=1). Above this display are two buttons, one which when clicked displays the contents of the next row, and the other displays the contents of the previous row. I want the change of display to occur without reloading the page or going to a new page.

My question is simply would I need to use AJAX for this?

答:
I do pretty much the same things that you have mentioned in your question. What I follow @ work is:

We use jQuery as javascripting framework. it helps us seamlessly write applications without having to worry about cross browser issues.

We develop single page based applications i.e we develop the application such that the UI is changed in response to user action without page reload. We use AJAX for these.

What we do is we make calls to the backend server and request for the dynamic data in json format. You can do these in jQuery using

```<code>//here you pass your entire document to the java script for manipulation
$(document).ready(function(){
      $('#id_of _ur_element_on_which_you_want_to_perform_ajax_call).getJSON(url,data,
                                                                          function(Data){
</code>```

//here Data is the response that you have got from the server...

//suppose you want to get the name from server so what you do is

```<code>       $('#id_of_input_field).val(Data.name);

   });
</code>```

})

with jQuery you need to do is make calls to the server and update the UI and for all these you just have to use the id of elements. As simple as that and the best part is no issue of cross browser compatibility.

Hope these helps. All the best.

Title: Will I need to use AJAX for this?

Body:
I do pretty much the same things that you have mentioned in your question. What I follow @ work is:

We use jQuery as javascripting framework. it helps us seamlessly write applications without having to worry about cross browser issues.

We develop single page based applications i.e we develop the application such that the UI is changed in response to user action without page reload. We use AJAX for these.

What we do is we make calls to the backend server and request for the dynamic data in json format. You can do these in jQuery using

//here you pass your entire document to the java script for manipulation
$(document).ready(function(){
      $('#id_of _ur_element_on_which_you_want_to_perform_ajax_call).getJSON(url,data,
                                                                          function(Data){

//here Data is the response that you have got from the server...

//suppose you want to get the name from server so what you do is

       $('#id_of_input_field).val(Data.name);

   });

})

with jQuery you need to do is make calls to the server and update the UI and for all these you just have to use the id of elements. As simple as that and the best part is no issue of cross browser compatibility.

Hope these helps. All the best.


问:
Are there any actual case studies on rewrites of software success/failure rates?
I've seen multiple posts about rewrites of applications being bad, people's experiences about it here on Programmers, and an article I've ready by Joel Spolsky on the subject, but no hard evidence or case studies.  Other than the two examples Joel gave and some other posts here, what do you do with a bad codebase and how do you decide what to do with it based on real studies?

For the case in point, there are two clients I know of that both have old legacy code.  They keep limping along with it because as one of them found out, a rewrite was a disaster, it was expensive and didn't really work to improve the code much.  That customer has some very complicated business logic as the rewriters quickly found out.

In both cases, these are mission critical applications that brings in a lot of revenue for the company.  The one that attempted the rewrite felt that they would hit a brick wall if the legacy software didn't get upgraded at some point in the future.  To me, that kind of risk warrants research and analysis to ensure a successful path.

Have there been actual case studies that have investigated this?  I wouldn't want to attempt a major rewrite without knowing some best practices, pitfalls, and successes based on actual studies.

Aftermath:  okay, after more searching, I did find three interesting articles on case studies:

Rewrite or Reuse.  They did a study on a Cobol app that was converted to Java.

The other was on Software Reuse: Developers Experiences and Perceptions.

Reuse or Rewrite Another study on costs of maintenance versus a rewrite.

I recently found another article on the subject: The Great Rewrite. There the author seems to hit on some of the major issues.  Along with this was the idea of prototyping by using the proposed new technology stack and measuring how quick the devs picked it up.  This was all as a prelude to a rewrite, which I thought was a great idea!

答:
There are many examples of companies that died of a rewrite, like Netscape. There are also companies that survived a rewrite without big trouble like twitter.

There aren't any quantified case studies, because it is not feasible to have a control experiment where you look at the business success of not rewriting versus the business success of rewriting. Every application is different.

There are some obvious cases where a rewrite makes sense and many cases where it doesn't. I've cooked up a little recipe to figure out if a rewrite would make sense in your case.

I think that rewrites make more sense nowadays because we're coding swiftly on the shoulders of ever improving invasive frameworks like Rails, Grails, AngularJS. If you want to move from plain js to Angular, a rewrite is about all you can do. It might still make tons of sense. If you're replacing one diy implementation with another (like all the examples in Joel Spolsky's article) you're probably crazy.


问:
What are non-programming mistakes that a programmer should avoid?
People make mistakes, even in the real life... Which should we, geeky programmers, avoid?</p>

答:
Learn how to listen to people (or users of your product).

Too many programmers are fast to jump to "this user is an idiot" instead of listening to what the person or user has to say.  There's something to learn from everyone in this world.


答:
A lot of these answers have focused on the question of programming languages.  And I agree, there will be few successful programmers that only learn one language.

But the question seems to me more about programming worlds.  And you can live successfully in within a world.  If your goal is to do Microsoft programming, you really don't need to know Java and the related frameworks.  But you might need to move from VB to C# to F#, etc.


问:
Is "regular" a technical term for a grammar?
Reading the Go language specs, I read in the intro:

"The grammar is compact and regular, allowing for easy analysis by automatic tools such as integrated development environments."

Is the word "regular" here a technical term, or should it be interpreted just as a vague English word?

答: "Regular" is a technical term for grammars, but I strongly doubt it is used with that meaning here as a regular grammar can describe only regular languages, which may also be described by regular expressions.</p>


答:
It's a technical term, but not the technical term you are thinking of.

In this case, "regular" means composed of few rules with with few corner cases.

The term for a grammar that describes a regular language is usually left-linear or right-linear, "regular grammar" in this sense is rather uncommon. A compact notation for describing regular languages are regular expressions.

Go's grammar is not in CH-3, i.e. not regular in that sense of the word, but it has a lot less corner cases than, say, Java, C#, C++ or C, so it is a lot more regular (in the other sense) than those.

Title: Is "regular" a technical term for a grammar?

Body:
Reading the Go language specs, I read in the intro:

"The grammar is compact and regular, allowing for easy analysis by automatic tools such as integrated development environments."

Is the word "regular" here a technical term, or should it be interpreted just as a vague English word?


问:
Violation of the C definition?
The C standard states that any character in the machine's standard printing set will never be negative.But the following code:

```<code>char c=1234;
printf("%d\t%c",c,c);
</code>```

gives a negative output and prints a strange character,meaning that the character is in machine's printing character set.Is the C standard being violated here?

答:
The C standard states that any character in the machine's standard printing set will never be negative.

Where? C++ has that constraint for characters in the basic execution character set (and not all printing characters, see 2.2/3 in C++98, 2.3/11 in C++11), but in the past I've looked for a similar clause for C and didn't found it.

Even for C++, if the character printed is a "strange character", that means it is probably not in the basic character set and thus the behavior by itself gives no hint about conformance. BTW, even if the glyph was similar to one in the basic character set, that wouldn't mean much, a 'A' for instance could be intended as an upper case alpha.

Title: Violation of the C definition?


问:
"A line comment acts like a newline"
I'm reading the Go language specification. The section on comments states:

Line comments start with the character sequence // and stop at the end of the line. A line comment acts like a newline.

What is the point of specifying that a line comment acts like a newline? Couldn't line comments simply act like empty strings?

Lines (except the last) end in a newline anyway, so any line (except the last) will act like two consecutive newlines. If the last line has a line comment, then it can also safely act like an empty string.

答:
Some potential reasons:

they consider the new line as part of the comment

they don't want any ambiguity, especially that there is another kind of comment which is sometimes equivalent to a space and sometimes equivalent to a new line.

Title: "A line comment acts like a newline"


问:
Sorting and averaging the highest values of pixel data
Currently, I am using Android/Java.  I am looking for the most efficient means to determine the average of the highest 100 pixel values taken from a greyscale preview.

The preview part I am more or less okay with; however, it determining which sorting methodology is the most efficient.  The other option is to apply a threshold, which will eliminate most of the data.

Which sorting algorithm would be most efficient for an unsorted data set of over 3 million values?

答:
You can implement a bounded PriorityQueue. It will sort the pixels by value, and remains only the pixels having higher values.

See for instance this SO question.

After having added all your pixels in the queue, only the X highers will remain in the queue, so you can simply get their mean value.

If your structure is able to add an element in O(log(n)) (has PriorityQueue does), to remove the lesser element in O(log(n)), the execution complexity in the worse case will be

O(n*log(n)) for adding all the pixels in the structure.

O(n) for computing the mean

So, the global complexity will be O(nlog(n)) + O(n) = O(nlog(n))

See also the Guava Min-Max Priority queue that retrieves the first and the last element in the queue in constant time, and that has an optional maximal size. This is, actualy, the class to use in your case.


答:
No, that is not a viable strategy -- at least not if you want to have identifiers as well as keywords in your language.

Let's say you have two rules: one for identifiers that consist of one or more arbitrary letters and one for some keyword that consists of letters. Let's take the keyword var for example. Now let's consider the input string var variant. If the identifier rule comes first in your lexer definition, this will be tokenized as two identifiers. Clearly that's not what we want, so let's put the keyword rule first. But now it's tokenized as two var keywords, followed by the identifier iant. That's also not what we want.

So there is no way to order the rules, such that we can get what we want here. However the maximal munch rule would give us exactly what we want in cases like this. Therefore it is preferable.

Title: Is this a viable approach to resolving multiple matches in a lexer?

Body:
I'm writing a lexer in JavaScript. It's pretty typical - rules are specified with regular expressions and produce a token.

I am unsure of the best way to handle when multiple rules are matched. The existing lexers I've looked at handle this by picking the rule with the longest match.

It also seems like a viable strategy, however, to simply use the first rule that matches. This is my current strategy.

Here is an example:

Input:

:=

Rules:

```<code>: -> COLON
= -> EQUALS
:= -> ASSIGN
</code>```

The longest-match rule would return ASSIGN, where the first-match rule would return COLON and then EQUALS.

Obviously this is not desirable, so under my implementation I would just reorder the rules to put the ASSIGN rule first as follows:

```<code>:= -> ASSIGN
: -> COLON
= -> EQUALS
</code>```

Is this a viable approach to just use the first matching rule? What are the advantages and disadvantages of each approach?


问:
I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?
My day job is  java/web developer. I have been using eclipse for ~5years. I think its excellent and I also use Webstorm for javascript and html/jsp.

I do on occasion need to ssh into server and mess around with config files; for this I use vi and it pains me. I have to get up a webpage listing the syntax/commands : press escape, then asterix, turn around three times and the text will be entered two lines above your cursor. Its so unintuitive to me, and I imagine anyone who grew up in the late eighties nineties.

Here are the main reasons I think eclipse is brilliant(and I assume other IDE's), and do not switch to emacs and/or vim.

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

availablity of 3rd party plugins - eg
findbugs/checkstyle.

One of the arguments I hear is that with emacs/vim you can create your own plugins - well OK, but you can do that in eclipse too. But you don't need to as everything is already there!  Its like saying buy this half built car, you can build the rest yourself.

Why are people using emacs/vim ? Do people who use it actually work on complex object-oriented projects in large organisations ?

What are the reasons to switch to vim/emacs. How would my productivity increase if I did switch?

答:
I am currently trying to switch from NetBeans to vim. Learning vim takes time and practice, but I see its advantages over, let's call them, "GUI editors" for certain cases.

But, unlike you, I am coding mostly Ruby, and I don't need all that code-generating, auto-completion, refactor-my-code black magic that NetBeans and Eclipse offer. If I were coding Java or C# I would most certainly not try to switch at all.


问:
Cross Compile Arm Program to Intel
I have searched around for a way to run a program meant for ARM processors on an Intel computer, but I can only find ways to do the reverse, to compile Intel programs for ARM. Are there any open-source cross-compilers that will allow me to do so? Thanks for your help.</p>

答:
Gcc can cross-compile programs for Intel targets from ARM hosts, but I'm not entirely sure that's what you meant to ask, because your terminology is off.  Let me lay out some general principles, which should hopefully either answer your question or give you enough information to clarify your question.

There are several different things to consider about cross compiling:

The host system.  This is the system that the compiler itself is installed on.

The target system.  This is the system that the executable will run on.  To fully specify it requires knowledge of a few different things:

The architecture.  ARM, x86, amd64, ppc, etc.

The operating system.  Android, iOS, Linux, OS X, Windows, etc.

The libraries.  Standard language libraries, GUI toolkits, etc. which also must be cross-compiled.

However, you also mention running a program designed for ARM on Intel, which isn't so much cross-compiling as porting.  Those are two very different things.  If you want to use your Intel machine to compile a program that will run on an Intel machine, that's porting, not cross-compiling.

Depending on how tightly the program is integrated with the operating system, architecture, and libraries, and how portable those were designed to be, this can be relatively easy or a complete nightmare.  A C program that only uses standard in and out is relatively easy to port to another platform.  Something tightly integrated with the platform, like Internet Explorer for example, is difficult enough to port that it's easier just to start from scratch.

If you clarify whether you actually meant cross-compiling or porting, and give more information on the operating systems and libraries involved, we might be able to help you in more depth.

Title: Cross Compile Arm Program to Intel


问:
Is Node.js correct choice for JSON parsing and IO driven
My program should perform following task:
It listen on http port after getting request it does following things.

Connect to gearman

Parse gearman payload to JSON (Upto 100 bytes)

Connect to Redis

Parse redis payload to JSON  (256 bytes to 10KB. 80% cases it will ~256 bytes)

Put some data in MySQL

Put data in Redis server

As my program seems to be IO driven. I have chosen nodesjs for developing. But after developing I am facing CPU hike related issue with nodejs.

My program taking 70%-100% cpu with 20 parallel clients. First I thought JSON parsing could be the issue. I was targetting near about 1K-3K request. As my redis server is able to process that may request in one second.

But for profiling I have started with one sample http server in node

Example code:

```<code>var http = require('http');
var url = require("url");
http.createServer(function (req, res) {
    var uri = url.parse(req.url).pathname;

    var body = "";

    req.on('data', function (chunk) {
        body += chunk;
    });

    req.on('end', function () {
        res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end('hi vivek');
    });

}).listen(9097, "127.0.0.1");
</code>```

Now my concern is with this hello world http server. Node CPU usage is spiking b/w 17%-20%.

```<code>My node version is v0.10.0
My OS is ubuntu 12.04
</code>```

My cpu information is

```<code>processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 23
model name  : Intel(R) Core(TM)2 Duo CPU     E8400  @ 3.00GHz
stepping    : 10
microcode   : 0xa07
cpu MHz     : 2992.491
cache size  : 6144 KB
physical id : 0
siblings    : 2
core id     : 0
cpu cores   : 2
apicid      : 0
initial apicid  : 0
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good nopl aperfmperf pni dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm sse4_1 xsave lahf_lm dtherm tpr_shadow vnmi flexpriority
bogomips    : 5984.98
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

processor   : 1
vendor_id   : GenuineIntel
cpu family  : 6
model       : 23
model name  : Intel(R) Core(TM)2 Duo CPU     E8400  @ 3.00GHz
stepping    : 10
microcode   : 0xa07
cpu MHz     : 2992.491
cache size  : 6144 KB
physical id : 0
siblings    : 2
core id     : 1
cpu cores   : 2
apicid      : 1
initial apicid  : 1
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep_good nopl aperfmperf pni dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm sse4_1 xsave lahf_lm dtherm tpr_shadow vnmi flexpriority
bogomips    : 5984.96
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:
</code>```

My questions are:

Is node correct choice for my problem description?

If nodejs is not correct choice for my problem description. What will be better alternative? As thread based approach will not scale for IO driven application.

How to find out what is causing that much CPU hike in complete integrated application and simple http program?

According to some node blog, I can support upto 10K parallel request with nodejs. But with if with only simple http server node is spiking b/w 20% cpu. How I will be able to support 10K user?

答:
Is node correct choice for my problem description?

Nodejs seems like a good fit to what you're doing. Node was built for exactly this sort of scenario. That's not to say other technologies wouldn't work as well.

Node is a young technology, and you often find yourself sacrificing comfort for performance. Often it's a lot more work, but once you learn how to work with it, it starts to be rewarding.

That said, other technologies might be able to accommodate your needs.

Pros for node

Fast

Optimized for this sort of IO driven task

Has an enthusiastic community which is very interested in helping beginners.

Fun to work with (That's totally subjective and is my personal opinion).

Cons for node

Often has less stable and mature drivers. If you're writing a production project, this is a biggie in my opinion.

New, sometimes has rough edges, sometimes APIs change.

Often requires tweaking and reading source code to get working in a satisfactory way.

Your task:

Connect to gearman

This node does nicely. node-gearman works nicely, it's pretty stable.

Parse gearman payload to JSON (Upto 100 bytes)

JS engines have been and will be extremely fast at parsing JSON. This is because JSON is a subset of JavaScript object literal notation (hence the name!). V8, which is the engine node runs on does JSON processing reliably fast.

Connect to Redis

node-redis lets you do that, it also works nicely.

Parse redis payload to JSON (256 bytes to 10KB. 80% cases it will ~256 bytes)

Again, JSON is not an issue to V8.

Put some data in MySQL

node-mysql is getting better, it still lacks support for prepared statements, but it does transactions, and emulates prepared statements with internal escaping.

Put data in Redis server

Again, node-redis