问:
Questions about Polymorphism
So I understand the importance of Polymorphism, including how vital it is.  But something I don't quite understand is what about the Constructor and any inherited Class the initial Base Class may have.

For example, I have a class to test some criteria- Level of account, Windows Version, and some other checks.

```<code>// Base Class
public class CheckInstalled : CheckUserLevel
{
       public CheckInstalled()
       {
             // Check verify the CheckUserLevel token is true, if it isn't throw an exception and close.
             if (!(_level == true))
             {
                    // The above implementation would technically go here.
             }
        }

        public virtual void IsInstalled()
        {
             // Implementation of initial check of general software.
        }
}
</code>```

So that would in theory be the Base Class which will do a Generic check; but there are other applications I need to test if they are installed.  So now I would create a Class for:

Sql

IIs

Dnn

Or whatever you may need to ensure is checked.  So for each of those Classes I'd inherit the CheckInstalled Class.  In each one I'd have this:

```<code>public override void IsInstalled()
{
      // Implementation to check for that specific Class Item is installed.
}
</code>```

So I see how Polymorphism will really simplify and keep each one of these Classes separate.  But will provide that flexibility for Object Orientation.

The root of my question, the Base Class Constructor contains that inherited token value. But do all other Classes that inherit the value?  Essentially that Base Class Constructor consistently execute? Or does the _level token have to be called in each?

Hopefully that makes sense.  If not please let me know and I'll try and rephrase it.

Update:

The _level is invoked here:

```<code>class CheckUserLevel
    {

        // Token Bool:
        private bool _level = false;

        #region Constructor:

        protected CheckUserLevel()
        {

            // Invoke Method On Creation:
            Elevate();

        }

        #endregion

        public void Elevate()
        {

            // Get Identity:
            WindowsIdentity user = WindowsIdentity.GetCurrent();

            // Set Principal
            WindowsPrincipal role = new WindowsPrincipal(user);

            #region Test Operating System for UAC:

            if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
            {

                // False:
                _level = false;

                // Todo: Exception/ Exception Log

            }

            #endregion

            else
            {

                #region Test Identity Not Null:

                if (user == null)
                {

                    // False:
                    _level = false;

                    // Todo: "Exception Log / Exception"

                }

                #endregion

                else
                {

                    #region Ensure Security Role:

                    if (!(role.IsInRole(WindowsBuiltInRole.Administrator)))
                    {

                        // False:
                        _level = false;

                        // Todo: "Exception Log / Exception"

                    }

                    else
                    {

                        // True:
                        _level = true;

                    }

                    #endregion

                } // Nested Else 'Close'

            } // Initial Else 'Close'

        } // End of Class.

    }
</code>```

The separate class actually generates the boolean value; as anytime that class is invoked it will assign a value to it.  I didn't want to expose too much with this class mostly because of its role in testing for Administration.

The problem:

Several methods will require Administrative Permission; my thought was to inherit on the base CheckInstalled.  Which in it's creation
  will automatically check the boolean state of _level.  Then from
  that point; this CheckInstalled can be inherited to other classes;
  then I can simply override IsInstalled to bend to the desired task
  for that item.

Is that a bad thought on my part?

答:
Two points; Firstly the constructor should generally be used for initial setup only. In your case it would loading any dependencies and suchlike, not doing the actual check.

Secondly (and more importantly) inheritance should be used in a case when you can share code between similar classes. This case dosent promote code reuse. Its a very good candidate for Interface usage, you can define an interface with CheckInstalled() then you can decouple the specific implementation. (for more reading have a look at the strategy pattern)

Title: Questions about Polymorphism


问:
Unit Testing DatabaseOpenHelper class in Android
I've written several unit tests for an already existing DatabaseOpenHelper class. I covered the creation scenario and migration from old schema to new one. Unfortunately, I don't feel that my tests are good. For example, for DB creation I check that SQLiteDatabase. execSQL() was called three times (we have three tables so far) and check that query string is in set of specified SQL strings.

The issue so far - if someone changes order of columns the test will fail. Probably this is OK.

But what are other ways of SQL schema unit testing? Or don't you have unit tests for that, and rely only on the integration one?

答:
When I faced this problem the road I walked sent me right into checking the database definition sentence with the expected one. This was broadly comparing a string with another one.

I recognized how absurd this was when I found myself getting the sentence from the code execution, checking it manually in notepad and inserting it in the test every time I made a change in the schema.

Right now I use integration test for the schema validation. In my case this involves exercising all persistance related operations (excluding performance-related ones).

I do not like the time required for this approach, but it is the best fair approach I have found.

ContentLicense: CC BY-SA 3.0


答:
```<code>// Base Class
internal class CheckInstalled : CheckUserLevel
{
    public CheckInstalled()
    {
        // Check verify the CheckUserLevel token is true, if it isn't throw an exception and close.
        if (!Verified)
         {
                // The above implementation would technically go here.
         }
    }

    public virtual void IsInstalled()
    {
        // Implementation of initial check of general software.
    }
}

internal class CheckUserLevel
{
    //Derived classes inherit the Verified property
    public bool Verified {get;set;}//Verified is more indicative of the action.  _level implies an enumeration of sorts

    public CheckUserLevel()//the base constructor is called prior to the derived constructor.          {
        Verify();//Caution: long running operations should not go in constructors
    }

    private void Verify()
    {
        bool verified = true;
        //do work

        Verified = verified;
    }
}
</code>```

The base constructor is called anytime a derived class is instantiated.  For this and other reasons, CheckUserLevel should be a has-a relationship.  In other words, CheckuserLevel should be a Member of CheckInstalled.

However, because it appears that you do not want to bind verification to construction...

Or does the _level token have to be called in each?

...a static Member makes more sense.

In other words convert to:

```<code>// Base Class
internal class CheckInstalled
{
    public CheckInstalled()
    {
        // Check verify the CheckUserLevel token is true, if it isn't throw an exception and close.
        if (!CheckUserLevel.Verified)
         {
                // The above implementation would technically go here.
         }
    }

    public virtual void IsInstalled()
    {
        // Implementation of initial check of general software.
    }
}

internal class CheckUserLevel
{
    public static bool Verified {get;set;}

    static CheckUserLevel()
    {
        Verify();
    }

    private static void Verify()
    {
        bool verified = true;
        //do work

        Verified = verified;
    }
}
</code>```

Title: Questions about Polymorphism

Body:
So I understand the importance of Polymorphism, including how vital it is.  But something I don't quite understand is what about the Constructor and any inherited Class the initial Base Class may have.

For example, I have a class to test some criteria- Level of account, Windows Version, and some other checks.

```<code>// Base Class
public class CheckInstalled : CheckUserLevel
{
       public CheckInstalled()
       {
             // Check verify the CheckUserLevel token is true, if it isn't throw an exception and close.
             if (!(_level == true))
             {
                    // The above implementation would technically go here.
             }
        }

        public virtual void IsInstalled()
        {
             // Implementation of initial check of general software.
        }
}
</code>```

So that would in theory be the Base Class which will do a Generic check; but there are other applications I need to test if they are installed.  So now I would create a Class for:

Sql

IIs

Dnn

Or whatever you may need to ensure is checked.  So for each of those Classes I'd inherit the CheckInstalled Class.  In each one I'd have this:

```<code>public override void IsInstalled()
{
      // Implementation to check for that specific Class Item is installed.
}
</code>```

So I see how Polymorphism will really simplify and keep each one of these Classes separate.  But will provide that flexibility for Object Orientation.

The root of my question, the Base Class Constructor contains that inherited token value. But do all other Classes that inherit the value?  Essentially that Base Class Constructor consistently execute? Or does the _level token have to be called in each?

Hopefully that makes sense.  If not please let me know and I'll try and rephrase it.

Update:

The _level is invoked here:

```<code>class CheckUserLevel
    {

        // Token Bool:
        private bool _level = false;

        #region Constructor:

        protected CheckUserLevel()
        {

            // Invoke Method On Creation:
            Elevate();

        }

        #endregion

        public void Elevate()
        {

            // Get Identity:
            WindowsIdentity user = WindowsIdentity.GetCurrent();

            // Set Principal
            WindowsPrincipal role = new WindowsPrincipal(user);

            #region Test Operating System for UAC:

            if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
            {

                // False:
                _level = false;

                // Todo: Exception/ Exception Log

            }

            #endregion

            else
            {

                #region Test Identity Not Null:

                if (user == null)
                {

                    // False:
                    _level = false;

                    // Todo: "Exception Log / Exception"

                }

                #endregion

                else
                {

                    #region Ensure Security Role:

                    if (!(role.IsInRole(WindowsBuiltInRole.Administrator)))
                    {

                        // False:
                        _level = false;

                        // Todo: "Exception Log / Exception"

                    }

                    else
                    {

                        // True:
                        _level = true;

                    }

                    #endregion

                } // Nested Else 'Close'

            } // Initial Else 'Close'

        } // End of Class.

    }
</code>```

The separate class actually generates the boolean value; as anytime that class is invoked it will assign a value to it.  I didn't want to expose too much with this class mostly because of its role in testing for Administration.

The problem:

Several methods will require Administrative Permission; my thought was to inherit on the base CheckInstalled.  Which in it's creation
  will automatically check the boolean state of _level.  Then from
  that point; this CheckInstalled can be inherited to other classes;
  then I can simply override IsInstalled to bend to the desired task
  for that item.

Is that a bad thought on my part?

Body:
// Base Class
internal class CheckInstalled : CheckUserLevel
{
    public CheckInstalled()
    {
        // Check verify the CheckUserLevel token is true, if it isn't throw an exception and close.
        if (!Verified)
         {
                // The above implementation would technically go here.
         }
    }

    public virtual void IsInstalled()
    {
        // Implementation of initial check of general software.
    }
}

internal class CheckUserLevel
{
    //Derived classes inherit the Verified property
    public bool Verified {get;set;}//Verified is more indicative of the action.  _level implies an enumeration of sorts

    public CheckUserLevel()//the base constructor is called prior to the derived constructor.          {
        Verify();//Caution: long running operations should not go in constructors
    }

    private void Verify()
    {
        bool verified = true;
        //do work

        Verified = verified;
    }
}

The base constructor is called anytime a derived class is instantiated.  For this and other reasons, CheckUserLevel should be a has-a relationship.  In other words, CheckuserLevel should be a Member of CheckInstalled.

However, because it appears that you do not want to bind verification to construction...

Or does the _level token have to be called in each?

...a static Member makes more sense.

In other words convert to:

// Base Class
internal class CheckInstalled
{
    public CheckInstalled()
    {
        // Check verify the CheckUserLevel token is true, if it isn't throw an exception and close.
        if (!CheckUserLevel.Verified)
         {
                // The above implementation would technically go here.
         }
    }

    public virtual void IsInstalled()
    {
        // Implementation of initial check of general software.
    }
}

internal class CheckUserLevel
{
    public static bool Verified {get;set;}

    static CheckUserLevel()
    {
        Verify();
    }

    private static void Verify()
    {
        bool verified = true;
        //do work

        Verified = verified;
    }
}


问:
Server side JavaScript rendering
I have almost a 'best-practice' question that's been nagging at me for a while.

When I use JavaScript libraries and APIs such as JQGrid or Google Maps, I tend to find myself creating server side libraries to render the JavaScript for me.

For example I might have:

```<code>$map->setZoom(10);
$map->setDimensions(200,250);
</code>```

in PHP, which would internally render the relevant JS when I call $map->render();, for example.

This means I can easily generate JavaScript based on the state of my applications. I also find it easier to work with the data I already have in my controllers etc.

Is this a suitable way of using common functionality within a JavaScript library or would it be better to write JS as standard?

答:
First issue: code quality

How do you:

unit test,

debug,

review for security issues,

this generated code?

The issue is the same for any generated code.That's why code generation tools are used only for simplistic tasks where the code is mostly boilerplate.

For example in .NET world, Visual Studio generates code for Windows Forms and is limited to positioning and customizing controls, but nothing technically challenging. In the same way, Entity Framework generates the mappings for the database, which means lines and lines of boilerplate, uninteresting, monotonous code.

Second issue: performance

If the code is generated, how do you cache it? Is it at least cached? If not, have you measured the precise impact on the performance, compared to the correctly-cached static JavaScript code? What about the impact on the server which needs to generate this code and how does it scale?

This issue may be non-existent in some cases (or at least the slight performance impact is very limited by severe caching, and a few milliseconds spent by the server generating the files is outweighed by the gains in terms of time you spend writing code), but you still need to measure the impact to know exactly how is it affecting your application.

Third issue: lower interoperability

JavaScript code written in JavaScript can be used no matter which framework is used server-side. JavaScript code I've written for an ASP.NET MVC website two years ago can still be used for a new website in Python.

If the code is generated server-side using server side programming language, you won't be able to reuse the same code in websites powered by other programming languages. Moreover, even migrating to newer versions of the same framework may be painful.

Title: Server side JavaScript rendering


问:
Changing __class__ in a factory?
I'm parsing a set of XML files of different kinds (these kinds are known in advance).

These are my requirements:

I want an object to represent each XML document (object-xml mapping)

I'd rather have a different class for each kind, so that identifying the type of the XML file is equivalent to looking at the class of the instance

I don't know the kind in advance

I want some specific behaviour for each object

But for the sake of simplicity, let's consider, I just need to open different numbers, of two know kinds:

even number

odd number

In term of design pattern, I use a variation of the factory design pattern, where the afctory is in the __init__ of the top level class, and I set the correct implementaion by a changing __class__ dynamically

```<code>class Number():
    def __init__(self, val):
        # common implementation (in case of XML, I do the recursion of xml imports)
        self.value = val

        # This is also the point where I discover the type of my object
        # Hence, the constuctor is also a factory of the appropriate type
        if val % 2 == 0:
            self.__class__ = EvenNumber
        elif val % 2 == 1:
            self.__class__ = OddNumber
        else:
            # keep the default Number implementation
            pass

class EvenNumber(Number):
    def half(self):
        '''
        specific behaviour for even numbers
        '''
        return self.value / 2

class OddNumber(Number):
    def next_int(self):
        return self.value

if __name__ == '__main__':
    for x in (Number(2), Number(3)):
        '''
        In the main algorithm, the processing depends on the type of the object
        '''
        if isinstance(x, EvenNumber):
            print(x.half())
        elif isinstance(x, OddNumber):
            print(x.next_int())
</code>```

What do you think about this approach?

I knew __class__ could be read, and was very surprised it can also be written.
What do you think of  changing __class__ dynamically?

Is this a well-known design pattern (it is not the factory pattern nor the state pattern nor the strategy pattern, even if it seems related to all of them)

Edit My real use-case

I want to open  a XBRL taxonomy, which is made of XML linkbases. Except the generic XML Linkbase, I want to handle more precisely some of them:

XML Label linkbase

XML Definition linkbase

etc.

In substance, here is what I have done:

```<code>class Linkbase(etree.xml.ElementTree):
    '''
    Generic linkbase
    '''
    def __init__(self, filename):
        # parse XML
        if self.type == 'definition':
            self.__class__ = DefinitionLinkbase
        elif self.type == 'label':
            self.__class__ = LabelLinkbase

     @property
     def type(self):
        return self.find('//xpath/expression').tag

class LabelLinkbase(Linkbase):
   @property
   def labels(self):
     # find all appropriate elements and returns a list of Labels

class DefintionLinkbase(Linkbase):
   @property
   def definitions(self):
      # returns all definitions
</code>```

Alternatively, I could have used a factory. I can think of something like this, but it doesn't look as elegant as the first approach.

```<code>class Linkbase(etree.xml.ElementTree):
    '''
    Generic linkbase
    '''
    def __init__(self, tree):
        self.tree = tree

     @property
     def type(self):
        return get_type(self.etree)

class LabelLinkbase(Linkbase):
   @property
   def labels(self):
     # find all appropriate elements and returns a list of Labels

class DefintionLinkbase(Linkbase):
   @property
   def definitions(self):
      # returns all definitions

def build_Linkbase(file):
    tree = etree.parse(file)
    if get_type(tree)== "defintion"
       return DefintionLinkbase(tree)
    elif get_type(tree) == "label":
       return LabelLinkbase(tree)
    else:
       return Linkbase(tree)
def get_type(tree):
    return tree.find('//xpath/expression').tag
</code>```

答:
You can do this:

```<code>class MetaNumber(type):
    subclasses = {}

    def __init__(cls, name, bases, dict):
        super(MetaNumber, cls).__init__(name, bases, dict)

        # if the subclass has an attribute named type
        # store it
        try:
            type = cls.type
        except AttributeError:
            pass
        else:
            MetaNumber.subclasses[cls.type] = cls

    def __call__(cls, value):
        # lookup the appropriate type
        subclass = MetaNumber.subclasses[value % 2]
        # substitute subclass
        return super(MetaNumber, subclass).__call__(value)

class Number(object):
    __metaclass__ = MetaNumber

    def __init__(self, val):
        self.value = val

class EvenNumber(Number):
    type = 0

    def half(self):
        '''
        specific behaviour for even numbers
        '''
        return self.value / 2

class OddNumber(Number):
    type = 1

    def next_int(self):
        return self.value
</code>```

This way:

You don't have to modify __class__ of already constructed objects

There is no duplication in fetching the type, because only the __call__ method checks it

Simply defining the subclass with an appropriate type class attribute is sufficient to give it support.

Title: Changing __class__ in a factory?

Body:
You can do this:

class MetaNumber(type):
    subclasses = {}

    def __init__(cls, name, bases, dict):
        super(MetaNumber, cls).__init__(name, bases, dict)

        # if the subclass has an attribute named type
        # store it
        try:
            type = cls.type
        except AttributeError:
            pass
        else:
            MetaNumber.subclasses[cls.type] = cls

    def __call__(cls, value):
        # lookup the appropriate type
        subclass = MetaNumber.subclasses[value % 2]
        # substitute subclass
        return super(MetaNumber, subclass).__call__(value)

class Number(object):
    __metaclass__ = MetaNumber

    def __init__(self, val):
        self.value = val

class EvenNumber(Number):
    type = 0

    def half(self):
        '''
        specific behaviour for even numbers
        '''
        return self.value / 2

class OddNumber(Number):
    type = 1

    def next_int(self):
        return self.value

This way:

You don't have to modify __class__ of already constructed objects

There is no duplication in fetching the type, because only the __call__ method checks it

Simply defining the subclass with an appropriate type class attribute is sufficient to give it support.


问:
What is the advantage of currying?
I just learned about currying, and while I think I understand the concept, I'm not seeing any big advantage in using it.

As a trivial example I use a function that adds two values (written in ML). The version without currying would be

```<code>fun add(x, y) = x + y
</code>```

and would be called as

```<code>add(3, 5)
</code>```

while the curried version is

```<code>fun add x y = x + y
(* short for val add = fn x => fn y=> x + y *)
</code>```

and would be called as

```<code>add 3 5
</code>```

It seems to me to be just syntactic sugar that removes one set of parentheses from defining and calling the function. I've seen currying listed as one of the important features of a functional languages, and I'm a bit underwhelmed by it at the moment. The concept of creating a chain of functions that consume each a single parameter, instead of a function that takes a tuple seems rather complicated to use for a simple change of syntax.

Is the slightly simpler syntax the only motivation for currying, or am I missing some other advantages that are not obvious in my very simple example? Is currying just syntactic sugar?

答: The primary reasoning I can think of (and I'm not an expert on this subject by any means) begins to show its benefits as the functions move from trivial to non-trivial. In all trivial cases with most concepts of this nature you'll find no real benefit. However, most functional languages make heavy use of the stack in processing operations. Consider PostScript or Lisp as examples of this. By making use of currying, functions can be stacked more effectively and this benefit becomes apparent as the operations grow less and less trivial. In the curried manner, the command and arguments can be thrown on the stack in order and popped off as needed so they are run in the proper order.</p>

Title: What is the advantage of currying?


答:
Currying is not just syntactic sugar!

Consider the type signatures of add1 (uncurried) and add2 (curried):

```<code>add1 : (int * int) -> int
add2 : int -> (int -> int)
</code>```

(In both cases, the parentheses in the type signature are optional, but I've included them for clarity's sake.)

add1 is a function that takes a 2-tuple of int and int and returns an int.  add2 is a function that takes an int and returns another function that in turn takes an int and returns an int.

The essential difference between the two becomes more visible when we specify function application explicitly.  Let's define a function (not curried) that applies its first argument to its second argument:

```<code>apply(f, b) = f b
</code>```

Now we can see the difference between add1 and add2 more clearly.  add1 gets called with a 2-tuple:

```<code>apply(add1, (3, 5))
</code>```

but add2 gets called with an int and then its return value is called with another int:

```<code>apply(apply(add2, 3), 5)
</code>```

EDIT:  The essential benefit of currying is that you get partial application for free.  Lets say you wanted a function of type int -> int (say, to map it over a list) that added 5 to its parameter.  You could write addFiveToParam x = x+5, or you could do the equivalent with an inline lambda, but you could also much more easily (especially in cases less trivial than this one) write add2 5!

Title: What is the advantage of currying?

Body:
I just learned about currying, and while I think I understand the concept, I'm not seeing any big advantage in using it.

As a trivial example I use a function that adds two values (written in ML). The version without currying would be

```<code>fun add(x, y) = x + y
</code>```

and would be called as

```<code>add(3, 5)
</code>```

while the curried version is

```<code>fun add x y = x + y
(* short for val add = fn x => fn y=> x + y *)
</code>```

and would be called as

```<code>add 3 5
</code>```

It seems to me to be just syntactic sugar that removes one set of parentheses from defining and calling the function. I've seen currying listed as one of the important features of a functional languages, and I'm a bit underwhelmed by it at the moment. The concept of creating a chain of functions that consume each a single parameter, instead of a function that takes a tuple seems rather complicated to use for a simple change of syntax.

Is the slightly simpler syntax the only motivation for currying, or am I missing some other advantages that are not obvious in my very simple example? Is currying just syntactic sugar?

Body:
Currying is not just syntactic sugar!

Consider the type signatures of add1 (uncurried) and add2 (curried):

add1 : (int * int) -> int
add2 : int -> (int -> int)

(In both cases, the parentheses in the type signature are optional, but I've included them for clarity's sake.)

add1 is a function that takes a 2-tuple of int and int and returns an int.  add2 is a function that takes an int and returns another function that in turn takes an int and returns an int.

The essential difference between the two becomes more visible when we specify function application explicitly.  Let's define a function (not curried) that applies its first argument to its second argument:

apply(f, b) = f b

Now we can see the difference between add1 and add2 more clearly.  add1 gets called with a 2-tuple:

apply(add1, (3, 5))

but add2 gets called with an int and then its return value is called with another int:

apply(apply(add2, 3), 5)

EDIT:  The essential benefit of currying is that you get partial application for free.  Lets say you wanted a function of type int -> int (say, to map it over a list) that added 5 to its parameter.  You could write addFiveToParam x = x+5, or you could do the equivalent with an inline lambda, but you could also much more easily (especially in cases less trivial than this one) write add2 5!


答:
Currying may be useful if you have a function that you are passing around as a first class object, and you don't receive all of the parameters needed to evaluate it in one place in the code.  You can simply apply one or more parameters when you get them and pass the result to another piece of code that has more parameters and finish evaluating it there.

The code to accomplish this is going to be simpler than if you need to get all the parameters together first.

Also, there is the possibility of more code reuse, since functions taking a single parameter (another curried function) don't have to match as specifically with all the parameters.

Title: What is the advantage of currying?


问:
Does a BSD-licensed project need a signed statement from each contributor?
Today I read on Fossil SCM's mailing list:

The problem with BSD is that you really should get a signed form from each
  contributor stating that their contribution is BSD.  This is automatic with
  GPL, since releasing your contributions under a compatible license is a
  prerequisite for viewing the code in GPL.  This makes GPL great for a
  highly collaborative environment, with lots of contributors.  BSD is more
  permissive (less burdensome) for readers, but that makes it a little
  tougher for writers since they now have to send in some paperwork.

Could someone explain why, and what are the possible consequences  of not having such a signed statement from project's contributors?

答:
BSD allows derived works that are not, as a whole, BSD-licensed. The danger here is that a new contributor (or, really, any contributor) could submit a code contribution and then later claim that his contribution was not BSD-licensed. Whether this would hold up in court probably depends a lot on the exact circumstances of the transfer -- imagine an ambiguous case where someone posts a patch to a mailing list and simply says, "Look at this neat new feature I wrote!" without expressly granting it to the project under a BSD license. (A project that requires signed agreements would respond, "Thank you, but before we can accept this into our code base, please legally acknowledge that your contribution is BSD-licened".)

A GPL-licensed project is less vulnerable to such ambiguity. The relevant legal teeth in the GPL are in section 8:

You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License...

In my example of an ambiguous contribution, there is no ambiguity with the GPL. The modified work is necessarily GPL-licensed, and the contributor could not post his modification to the mailing list without granting GPL rights to it (since posting his modified version constitutes a transfer). Any attempt to argue otherwise requires him to actively claim that he was violating the GPL, which means he loses rights to the project entirely and his modified work is legally void.

(I'm not a lawyer, so I'm not sure if the GPL's protections are sufficient to protect a project from a litigant that doesn't care about any amount of legal damage to himself, but it's certainly enough to deter most sane people from pressing legal action.)


答:
With curried functions you get easier reuse of more abstract functions, since you get to specialize. Let's say that you have an adding function

```<code>add x y = x + y
</code>```

and that you want to add 2 to every member of a list. In Haskell you would do this:

```<code>map (add 2) [1, 2, 3] -- gives [3, 4, 5]
-- actually one could just do: map (2+) [1, 2, 3], but that may be Haskell specific
</code>```

Here the syntax is lighter than if you had to create a function add2

```<code>add2 y = add 2 y
map add2 [1, 2, 3]
</code>```

or if you had to make an anonymous lambda function:

```<code>map (\y -> 2 + y) [1, 2, 3]
</code>```

It also allows you to abstract away from different implementations. Let's say you had two lookup functions. One from a list of key/value pairs and a key to a value and another from a map from keys to values and a key to a value, like this:

```<code>lookup1 :: [(Key, Value)] -> Key -> Value -- or perhaps it should be Maybe Value
lookup2 :: Map Key Value -> Key -> Value
</code>```

Then you could make a function that accepted a lookup function from Key to Value. You could pass it any of the above lookup function, partially applied with either a list or a map, respectively:

```<code>myFunc :: (Key -> Value) -> .....
</code>```

In conclusion: currying is good, because it lets you specialize/partially apply functions using a lightweight syntax and then pass these partially applied functions around to higher order function such as map or filter. Higher order functions (which take functions as parameters or yield them as results) are the bread and butter of functional programming, and currying and partially applied functions enable higher order functions to be used much more effectively and concisely.

Title: What is the advantage of currying?

Body:
With curried functions you get easier reuse of more abstract functions, since you get to specialize. Let's say that you have an adding function

add x y = x + y

and that you want to add 2 to every member of a list. In Haskell you would do this:

map (add 2) [1, 2, 3] -- gives [3, 4, 5]
-- actually one could just do: map (2+) [1, 2, 3], but that may be Haskell specific

Here the syntax is lighter than if you had to create a function add2

add2 y = add 2 y
map add2 [1, 2, 3]

or if you had to make an anonymous lambda function:

map (\y -> 2 + y) [1, 2, 3]

It also allows you to abstract away from different implementations. Let's say you had two lookup functions. One from a list of key/value pairs and a key to a value and another from a map from keys to values and a key to a value, like this:

lookup1 :: [(Key, Value)] -> Key -> Value -- or perhaps it should be Maybe Value
lookup2 :: Map Key Value -> Key -> Value

Then you could make a function that accepted a lookup function from Key to Value. You could pass it any of the above lookup function, partially applied with either a list or a map, respectively:

myFunc :: (Key -> Value) -> .....

In conclusion: currying is good, because it lets you specialize/partially apply functions using a lightweight syntax and then pass these partially applied functions around to higher order function such as map or filter. Higher order functions (which take functions as parameters or yield them as results) are the bread and butter of functional programming, and currying and partially applied functions enable higher order functions to be used much more effectively and concisely.


问:
More comfortable working on the backend, often referred for role on the front end
I have applied and have been approached for different roles in web development recently. The one thing that keeps coming up is that I am more suited to front end development than back end development.  This makes sense given my background starting out as a designer.

The problem is that while I have worked on a large app using ExtJS, I found designing and developing in ExtJS really frustrating. Oddly enough, it was working on this project that landed me in web development because my coding skills were recognized by some senior developers. I highlight that in my CV but I wonder if this might be a mistake.

I also use JavaScript quite a bit outside of web development. Specifically in Photoscript and InDesign to create batch operations.  It's often assumed that I have expert knowledge in JavaScript, whereas I'm only just getting to grips with the OOP style of JavaScript.  I use a lot of procedural code or I just use libraries like jQuery and Google Maps. I have created some experimental apps in Node and Knockout which I fortunately have enjoyed although Node is back end. I used to avoid JavaScript and jQuery in certain web projects since I was focusing on SEO and would only use Javascript if I really needed it.

During the interviews, I'm asked questions about JavaScript and front-end development.  But I really wanted to talk about PHP and the server side development, so I guess my background shows. How do I address this when I am either contacted for a role or I applying directly without selling my short?

答:
Consider that you are evaluating your interests and skills with respect to each other.  Employers are evaluating your skills relative to other applicants.  In other words, maybe you feel better suited for back end work, but maybe the interviewer has lots of qualified back end workers and has had trouble finding people with front end skills as good as yours.

My first job was at Taco Bell.  I almost always got put into the "back ups" position, the guy who heats up and refills all the ingredients.  I hated getting pigeon holed into there until one day I complained and my manager told me I was the only one with the planning skills to keep up with it properly.  Conversely, he had lots of people who could easily fill the slots I thought were more "fun."  That made me feel a lot better.

At my current job, I was often getting pigeon holed into the "glue" layers.  My manager pointed out that he doesn't have very many people who understand both the top and the bottom layers.  Sometimes what we want to do doesn't match up with what the company most needs us to do.

So, how to resolve it?  Just express your preferences.  That's what performance reviews and such are for.  I told my manager that I prefer the lower layers and eventually he was able to gravitate me mostly towards those tasks, but when he can't, at least I can feel good that he feels I am the one most suited to a glue layer task.  He is being cognizant of my abilities, not merely ignoring my interests.

OwnerDisplayName: anon


答:
The practical answer is that currying makes creating anonymous functions much easier. Even with a minimal lambda syntax, it's something of a win; compare:

```<code>map (add 1) [1..10]
map (\ x -> add 1 x) [1..10]
</code>```

If you have an ugly lambda syntax, it's even worse. (I'm looking at you, JavaScript, Scheme and Python.)

This becomes increasingly useful as you use more and more higher-order functions. While I use more higher-order functions in Haskell than in other languages, I've found I actually use the lambda syntax less because something like two thirds of the time, the lambda would just be a partially applied function. (And much of the other time I extract it into a named function.)

More fundamentally, it isn't always obvious which version of a function is "canonical". For example, take map. The type of map can be written in two ways:

```<code>map :: (a -> b) -> [a] -> [b]
map :: (a -> b) -> ([a] -> [b])
</code>```

Which one is the "correct" one? It's actually hard to say. In practice, most languages use the first one--map takes a function and a list and returns a list. However, fundamentally, what map actually does is map normal functions to list functions--it takes a function and returns a function. If map is curried, you don't have to answer this question: it does both, in a very elegant way.

This becomes especially important once you generalize map to types other than list.

Also, currying really isn't very complicated. It's actually a bit of a simplification over the model most languages use: you don't need any notion of functions of multiple arguments baked into your language. This also reflects the underlying lambda calculus more closely.

Of course, ML-style languages do not have a notion of multiple arguments in curried or in uncurried form. The f(a, b, c) syntax actually corresponds to passing in the tuple (a, b, c) into f, so f still only takes on argument. This is actually a very useful distinction that I wish other languages would have because it makes it very natural to write something like:

```<code>map f [(1,2,3), (4,5,6), (7, 8, 9)]
</code>```

You couldn't easily do this with languages that have the idea of multiple arguments baked right in!

Title: What is the advantage of currying?

Body:
The practical answer is that currying makes creating anonymous functions much easier. Even with a minimal lambda syntax, it's something of a win; compare:

map (add 1) [1..10]
map (\ x -> add 1 x) [1..10]

If you have an ugly lambda syntax, it's even worse. (I'm looking at you, JavaScript, Scheme and Python.)

This becomes increasingly useful as you use more and more higher-order functions. While I use more higher-order functions in Haskell than in other languages, I've found I actually use the lambda syntax less because something like two thirds of the time, the lambda would just be a partially applied function. (And much of the other time I extract it into a named function.)

More fundamentally, it isn't always obvious which version of a function is "canonical". For example, take map. The type of map can be written in two ways:

map :: (a -> b) -> [a] -> [b]
map :: (a -> b) -> ([a] -> [b])

Which one is the "correct" one? It's actually hard to say. In practice, most languages use the first one--map takes a function and a list and returns a list. However, fundamentally, what map actually does is map normal functions to list functions--it takes a function and returns a function. If map is curried, you don't have to answer this question: it does both, in a very elegant way.

This becomes especially important once you generalize map to types other than list.

Also, currying really isn't very complicated. It's actually a bit of a simplification over the model most languages use: you don't need any notion of functions of multiple arguments baked into your language. This also reflects the underlying lambda calculus more closely.

Of course, ML-style languages do not have a notion of multiple arguments in curried or in uncurried form. The f(a, b, c) syntax actually corresponds to passing in the tuple (a, b, c) into f, so f still only takes on argument. This is actually a very useful distinction that I wish other languages would have because it makes it very natural to write something like:

map f [(1,2,3), (4,5,6), (7, 8, 9)]

You couldn't easily do this with languages that have the idea of multiple arguments baked right in!


问:
How do programming languages benefit from being based on English?
I think the world now programs in English-based programming languages not only because of historical/economic circumstances, but because the English morphology in particular has some properties that suit algorithmic thinking best. But anyway it would be interesting to hear your opinions on this, especially if you are multilingual yourself.

I've seen some mentioning of German-based languages (see Plankalkul for example, in fact the first ever programming language we know very little about, thanks to WW2), also a Russian-based flavor of Algol which existed back in the 80's at least on paper, not sure if it ever existed in binary or not. Both looked a bit sluggish because there were more shortened words and weird abbreviations than full words like in the EN-based languages. So if you know of any other national language-based PL's, even completely archaic and irrelevant today, purely theoretical or whatever, would be interesting to take a look at them.

And back to the main question: so what, if any, makes the Shakespeare's language so good for programming?

(There is actually a list of Non-English-based programming languages on Wikipedia (of course, where else?), but it would be interesting to hear opinions of native speakers of those languages on how a given "national" programming languages really feels like.)

答:
For some fun reading on the context of language and how we end up groking things:

Stuff of Thought by Steven Pinker

Remember, we're talking about the language construct, not how we communicate the information (not one in the same), I've worked with code where the main language for variables was all in German (the code was no less easy to understand). English doesn't inherently have anything that suits it better for programming, if we're going directly off of how our language is structured it is probably worse not better, and this could honestly be for many reasons:

Lack of structure (we can put subject/predicate/nouns/adjectives wherever we please),

Mutability of our words (we feel like we can abbreviate ANYTHING)

BIG ONE: Someone who knows English fluently won't have any better understanding of a section of code than someone who has no understanding of the English language.

Asking why programming languages use "English" is like asking why the periodic table still has the letter 'W' identify Tungsten, most people can't tell you why unless they know the history.  And if you want the history of programming languages we should go back to punch cards, byte instructions, and assembly.

Assembly has no major "English" constructs but it's as close as you can get to machine code without hating yourself.  Further, all structural elements of higher level languages can and are regularly implemented by those of us crazy enough to enjoy it.  LD, MV, ST, BRA, and the rest of the instruction set look nothing like English, but I can read it perfectly and get the full meaning.

We assign the same meaning of the LD or MV in assembly to higher level constructs, I don't need to know what a variable means, and in many cases won't if it's in English anyway because of #2 in my list.  The set of identifiers like int, str, enum, and such are a way of telling what you're working with, no more.  If instead of int the identifier was seagull we'd all know what seagull meant in a coding context, not because it's English, but that's what the identifier covers.

TL;DR: Programming languages, like any language need training to understand.  The reason their commands are in English instead of Spanish or German or Russian is more than likely esoteric and historical than by some necessary construct of the English language being more or less suited for the identifiers in the Formal Language construct.

ContentLicense: CC BY-SA 2.5


答:
The GPL does not explicitly make any statement about the licensing of code contributed code back to the project.  It might be inferred that any contribution is covered by the GPL as it could be considered a derived work and thus must be licensed under the GPL but it is possible that the contribution is already licensed under an incompatible license and cannot be combined with the GPL code.

As far as I know the only license that explicitly mentions the licensing of contributed code is the Apache License (see "Contributions" and "Submission of Contributions").

That said, it is generally good practice to have all contributors to an Open Source project explicitly assign the copyright of their contributions to the project. The assignment form will also include text that affirms that the contributor is the copyright holder of the contribution and/or is authorized to assign the copyright.

By including the second part the project has some protection when it is discovered that someone contributed code that they were not legally permitted to contribute (e.g. they copied proprietary code from their employer).

The other general risk of not getting copyright assignment is that if, in the future you wish to change the license you can't without permission of all the contributors who hold the copyright on their contribution.  For example if you wanted to change the license from GPLv2 to LGPLv2 you could not without permission.

Title: Does a BSD-licensed project need a signed statement from each contributor?

Body:
Today I read on Fossil SCM's mailing list:

The problem with BSD is that you really should get a signed form from each
  contributor stating that their contribution is BSD.  This is automatic with
  GPL, since releasing your contributions under a compatible license is a
  prerequisite for viewing the code in GPL.  This makes GPL great for a
  highly collaborative environment, with lots of contributors.  BSD is more
  permissive (less burdensome) for readers, but that makes it a little
  tougher for writers since they now have to send in some paperwork.

Could someone explain why, and what are the possible consequences  of not having such a signed statement from project's contributors?


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
I started off from games programming. It all comes from NES days. Aspired to be game developer and I achieved it but changed to Application Software/Hardware Analyst for better career as my country for games industries is too niche.

During my early days, I actually felt a bit regret of entering into this IT roles. But later was inspired and influenced by my ex-colleagues on his accomplishments and they were quite active in these new technical development areas. During my free time, I will mingle with software programming to work on personal projects with my ex-colleagues.


答:
Currying allows flexible function composition.

I made up a function "curry". In this context, I don't care what kind of logger I get or where it comes from. I don't care what the action is or where it comes from. All I care about is processing my input.

```<code>var builder = curry(function(input, logger, action) {
     logger.log("Starting action");
     try {
         action(input);
         logger.log("Success!");
     }
     catch (err) {
         logger.logerror("Boo we failed..", err);
     }
});
var x = "My input.";
goGatherArgs(builder)(x); // Supplies action first, then logger somewhere.
</code>```

The builder variable is a function that returns a function that returns a function that takes my input that does my work. This is a simple useful example and not an object in sight.

Title: What is the advantage of currying?

Body:
Currying allows flexible function composition.

I made up a function "curry". In this context, I don't care what kind of logger I get or where it comes from. I don't care what the action is or where it comes from. All I care about is processing my input.

var builder = curry(function(input, logger, action) {
     logger.log("Starting action");
     try {
         action(input);
         logger.log("Success!");
     }
     catch (err) {
         logger.logerror("Boo we failed..", err);
     }
});
var x = "My input.";
goGatherArgs(builder)(x); // Supplies action first, then logger somewhere.

The builder variable is a function that returns a function that returns a function that takes my input that does my work. This is a simple useful example and not an object in sight.


答:
(I'll give examples in Haskell.)

When using functional languages it's very convenient that you can partially apply a function. Like in Haskell's (== x) is a function that returns True if its argument is equal to a given term x:

```<code>mem :: Eq a => a -> [a] -> Bool
mem x lst = any (== x) lst
</code>```

without currying, we'd have somewhat less readable code:

```<code>mem x lst = any (\y -> y == x) lst
</code>```

This is related to Tacit programming (see also Pointfree style on Haskell wiki). This style focuses not on values represented by variables, but on composing functions and how information flows through a chain of functions. We can convert our example into a form that doesn't use variables at all:

```<code>mem = any . (==)
</code>```

Here we view == as a function from a to a -> Bool and any as a function from a -> Bool to [a] -> Bool. By simply composing them, we get the result. This is all thanks to currying.

The reverse, un-currying, is also useful in some situations. For example, let's say we want to split a list into two parts - elements that are smaller than 10 and the rest, and then concatenate those two lists. Splitting of the list is done by partition (< 10) (here we also use curried <). The result is of type ([Int],[Int]). Instead of extracting the result into its first and second part and combining them using ++, we can do this directly by uncurrying ++ as

```<code>uncurry (++) . partition (< 10)
</code>```

Indeed, (uncurry (++) . partition (< 10)) [4,12,11,1] evaluates to [4,1,12,11].

There are also important theoretical advantages:

Currying is essential for languages that lack data types and have only functions, such as the lambda calculus. While these languages aren't useful for practical use, they're very important from a theoretical point of view.

This is connected with the essential property of functional languages - functions are first class object. As we've seen, the conversion from (a, b) -> c to a -> (b -> c) means that the result of the latter function is of type b -> c. In other words, the result is a function.

(Un)currying is closely connected to cartesian closed categories, which is a categorical way of viewing typed lambda calculi.

Title: What is the advantage of currying?

Body:
(I'll give examples in Haskell.)

When using functional languages it's very convenient that you can partially apply a function. Like in Haskell's (== x) is a function that returns True if its argument is equal to a given term x:

mem :: Eq a => a -> [a] -> Bool
mem x lst = any (== x) lst

without currying, we'd have somewhat less readable code:

mem x lst = any (\y -> y == x) lst

This is related to Tacit programming (see also Pointfree style on Haskell wiki). This style focuses not on values represented by variables, but on composing functions and how information flows through a chain of functions. We can convert our example into a form that doesn't use variables at all:

mem = any . (==)

Here we view == as a function from a to a -> Bool and any as a function from a -> Bool to [a] -> Bool. By simply composing them, we get the result. This is all thanks to currying.

The reverse, un-currying, is also useful in some situations. For example, let's say we want to split a list into two parts - elements that are smaller than 10 and the rest, and then concatenate those two lists. Splitting of the list is done by partition (< 10) (here we also use curried <). The result is of type ([Int],[Int]). Instead of extracting the result into its first and second part and combining them using ++, we can do this directly by uncurrying ++ as

uncurry (++) . partition (< 10)

Indeed, (uncurry (++) . partition (< 10)) [4,12,11,1] evaluates to [4,1,12,11].

There are also important theoretical advantages:

Currying is essential for languages that lack data types and have only functions, such as the lambda calculus. While these languages aren't useful for practical use, they're very important from a theoretical point of view.

This is connected with the essential property of functional languages - functions are first class object. As we've seen, the conversion from (a, b) -> c to a -> (b -> c) means that the result of the latter function is of type b -> c. In other words, the result is a function.

(Un)currying is closely connected to cartesian closed categories, which is a categorical way of viewing typed lambda calculi.


问:
How is C/C++ more difficult to decompile than C#?
See top answer here: Obfuscation at source-code level more effective than obfuscators?, specifically "Code it in a language so not easy to decompile such as C/C++"

I'm looking to write a new application that will be sold for $500 per license, so I'd like to prevent decompilers.

Should C# be avoided, or is using an obfuscator sufficient to prevent this sort of thing?

答:
C# assemblies contain metadata that c++ assemblies do not, which can aid in decompilation.  C# also compiles down to an intermediate language which maps much better to the original source code than does C++'s machine code output.  Obfuscators can help, but you can't prevent reverse-engineering; you can only make it harder.

In practice, nobody wants your code for free anyway. Companies want to be legitimately licensed; they don't want to go to the trouble (or legal exposure) of hacking your code to get a free license.  At $500 per license, it's unlikely you're targeting ordinary consumers, so the only ones who will be interested in hacking your software will be those folks who aren't in your target market anyway.

So take sensible precautions, like having a licensing scheme, install codes, phone home, or whatever the latest thing is for securing your software, and focus your efforts on adding new features to make your software better and more attractive, choosing the language that provides you with the best possible productivity.

NB: If you aren't getting ripped off occasionally by the hackers, your software isn't important enough.  At that point, you can probably hire someone to issue takedown notices and work on better technological solutions.


答:
Fundamentally, any executable program can be disassembled and inspected.  The ease with which a reverse engineer can recreate the original source code depends on how much information or meta-data about the original source code exists within the executable.  Can the reverse engineer discover the original variable names, functions, data structures, etc.?  A compiler essentially "compresses" source code, turning it into a format which is more amenable to machine execution, such as native machine code or byte code which is processed by an intermediate runtime.  But generally speaking, the compression is lossy, meaning that a lot of information about the original source code is simply not there.  However, certain compiler outputs are more lossy than others.

C and C++ generally compile directly to native machine code.  But neither the C nor C++ standard describes the layout of a binary executable created by the compiler.  An optimizing C++ compiler, for example, is free to do many things to increase performance, including optimizing out certain variable declarations or removing entire functions and classes.  Very little information about the original C++ code necessarily needs to exist in the binary executable.  A reverse engineer would still be able to disassemble it, but gleaning any C or C++ code out of the assembly would be an act of guessing and interpretation.

C#, however, compiles to CIL (Common Intermediate Language).  Typically, a lot more information about the original source code, such as object oriented concepts including class structure, can be gleaned from reading the CIL than from reading, let's say, highly optimized x86 machine code produced from a C++ compiler.

Title: How is C/C++ more difficult to decompile than C#?

Body:
See top answer here: Obfuscation at source-code level more effective than obfuscators?, specifically "Code it in a language so not easy to decompile such as C/C++"

I'm looking to write a new application that will be sold for $500 per license, so I'd like to prevent decompilers.

Should C# be avoided, or is using an obfuscator sufficient to prevent this sort of thing?


答:
Currying (partial application) lets you create a new function out of an existing function by fixing some parameters.  It is a special case of lexical closure where the anonymous function is just a trivial wrapper which passes some captured arguments to another function.  We can also do this by using the general syntax for making lexical closures, but partial application provides a simplified syntactic sugar.

This is why Lisp programmers, when working in a functional style, sometimes use libraries for partial application.

Instead of (lambda (x) (+ 3 x)), which gives us a function that adds 3 to its argument, you can write something like (op + 3), and so to add 3 to every element of a some list would then be (mapcar (op + 3) some-list) rather than (mapcar (lambda (x) (+ 3 x)) some-list). This op macro will make you a function which takes some arguments x y z ... and invokes (+ a x y z ...).

In many purely functional languages, partial application is ingrained into the syntax so that there is no op operator. To trigger partial application, you simply call a function with fewer arguments than it requires. Instead of producing an "insufficient number of arguments" error, the result is a function of the remaining arguments.

Title: What is the advantage of currying?


问:
How can I avoid using my own name in the identifiers, packages, or namespaces of open sources projects I create?
I do a lot of development in my own time. These projects I work on are all just for fun and learning (so far). I commonly do Java development with Maven but I have also been known to dabble in .NET and Python. All of the projects I work on use open source licenses, although most of them are not on any public code repositories.

Java/Maven development requires me to use a unique groupId (e.g. "com.mydomain") and a unique package (directory) structure, usually containing the groupId while .NET development encourages unique namespaces in which I use similar conventions to the Java package concept. To ensure uniqueness, I usually just use one of my domain names with the parts reversed (e.g. "ca.jessewebb"); I believe this is a very common practice.

I am in the initial stages of creating a new, open source, Java/Maven project (let's call it "newproj") and I would like to put it on GitHub. My username on GitHub is "jessewebb" so this will give it a URL like: https://github.com/jessewebb/newproj. I don't want to bother registering the "newproj.com" domain name so I decided to use "ca.jessewebb" and "ca.jessewebb.newproj" as the groupId and package, respectively.

It occurred to me that the presence of my personal identity in the code and as part of the project's home (in the GitHub URL) will likely cause a potential contributor to think twice about getting involved with my project. This is a problem, I don't want it to be my project. I would prefer if I could, instead, convey the message that I do not own the project. Now, in all honesty, it really isn't that big of a deal because I doubt my projects will garner much community involvement but I also see this as even more of a reason to avoid any possibility of deterring would-be contributors.

For another example, I created a Google Code project a few years ago (let's call it "oldproj"). When I created the project, I knew I was going to host it on Google Code so I used the groupId and package name of "com.googlecode.oldproj", which is the reverse of the default domain name Google Code provides every new project. This turned out to be a not-so-great idea; a year or so later, I moved the code to a different repo and I had to rename these identifiers (well I didn't have to but...). At the time, I didn't own any domain names and I ended up buying the domain name "oldproj.com" and I used it. I liked this because it gave the project its own identity and I wasn't stamping my name on the code everywhere. I could have just as easily registered the "jessewebb.ca" domain name and used "ca.jessewebb.oldproj" as the package name but I didn't because I had the same concerns back then too.

So my question is...

How can I avoid using my own (domain) names when creating open source projects while still maintaining uniqueness of packages/namespaces?

As projects gain more momentum, it makes sense to register the domain names but it seems silly and a waste of money to do this earlier on. I realize that I don't actually have to own the domain name to use it in the code but that feels wrong and can lead to a squatter snatching it from under you in the meantime. What do other people do about this dilemma? Are there examples of popular (widely used, large community, etc.) open source projects that contain the original developer's identity as part of its own identifier(s)?

答:
In my projects, I give them a name but not necessarily a domain. So my package names (and namespaces) are usually just "projectname.libraryname", regardless where the code is hosted.

I am used to .NET where this is handeled quite freely.


问:
Need some advice and feedback on my code's design
I am looking for feedback on the design of my program.

I have a shell script call function.sh that defines a lot of helper functions. My intent is to use those bash functions defined in functions.sh in a C program. I am doing this so that I don't have to rewrite the bash functionality (in functions.sh) again in C. I want to use one common library for functions I need (which is functions.sh).

Here is my C code and functions.sh

C code:

```<code>#include <stdlib.h>
#include <sys/wait.h>
#include <stdio.h>

void shellCall(char * command)
{
    int status, commandexitcode=0;
    if(command == NULL)
    {
        printf("NULL command string sent\n");
        exit(1);
    }

    status = system(command);

    if(status == -1)
    {
        printf("Error during call, value %d\n", status);
        exit(1);
    }

    if (WIFEXITED(status))
    {
        commandexitcode =  WEXITSTATUS(status);
        if (commandexitcode != 0)
        {
            printf("non zero exit code: %d\n", commandexitcode);
            exit(1);
        }
    }

    else
       if (WIFSIGNALED(status))
    ...
}

int main(int argc,char **argv)
{
    char  command[100]; //command
    int i = 0;

    for (i = 1 ; i <= 10 ; i++)
    {
        sprintf( command, "source $PWD/functions.sh ; i=%d ; myfunc %d", i,i );
        shellCall(command);
    }
}
</code>```

functions.sh:

```<code>#!/bin/sh
# functions.sh

myfunc()
{
    echo "I received $1"
}
</code>```

Please note that I have only shown a very simple example of the way I am using functions in functions.sh. In reality functions.sh has many functions, some of which implement decent logic.

My Questions - I need feedback on the following aspects.

Is it a bad programming practice ( something that will make experienced and senior developers mad when they see this) to use system() calls to call functions in functions.sh as I have done?

If it is a bad practice, what  are the reasons (technical and other) for which it is considered a bad programming practice?

What changes should I make to my C code so that experienced and senior developers will find it acceptable?

答:
Calling 'system()' has a huge amount of overhead. The OS has to spin up a new shell for each such call. Kudos for having done error checking on the return value of system(), but you can see how much more complex it makes your program. Furthermore, you need to add still more error checking. You need to check that the shell scripts are where you think they are before you call them with system(). If they're not where you expect them to be, or have the wrong permissions, your program is going to fail with user unfriendly messages.

You are making distribution and configuration of your program more complex. Not only do you have to distribute a binary, but you have to distribute the shell scripts as well and make sure they end up in the correct directory.

You don't explain why you are doing it this way, but in the absence of other information I'd suggest turning the whole thing inside out. Write a shell script that calls a few C programs to do any computationally intensive work.


问:
addIfNotExist alternative
Is there are any standards or conventions on naming methods which add something if it not exist into another something.

For example: Store.instance().addItemIfNotExist(item)

IfNotExist is really ugly part. What workaround may be?

答:
Some databases use the term Upsert to mean "Update or Insert as needed", but you may not want the Update aspect.

In general, an addItem() function has an implied, expected failure if the item already exists within the database, so you could use that.  Your error handling code after the addItem() call would make it clear that failure because of already existing was okay.

Finally, you could consider addItemExclusive() to better indicate that the routine will check for existence prior to adding the item.

Title: addIfNotExist alternative


答:
Currying is an advantage when you don't have all of the arguments for a function. If you happen to be fully evaluating the function, then there's no significant difference.

Currying lets you avoid mentioning not-yet-needed parameters. It is more concise, and doesn't require finding a parameter name that doesn't collide with another variable in scope (which is my favorite benefit).

For example, when using functions that take functions as arguments, you'll often find yourself in situations where you need functions like "add 3 to input" or "compare input to variable v". With currying, these functions are easily written: add 3 and (== v). Without currying, you have to use lambda expressions: x => add 3 x and x => x == v. The lambda expressions are twice as long, and have a small amount of busy work related to picking a name besides x if there's already an x in scope.

A side benefit of languages based on currying is that, when writing generic code for functions, you don't end up with hundreds of variants based on the number of parameters. For example, in C#, a 'curry' method would need variants for Func<R>, Func, Func<A1, A2, R>, Func<A1, A2, A3, R>, and so forth forever. In Haskell, the equivalent of a Func<A1, A2, R> is more like a Func<Tuple<A1, A2>, R> or a Func<A1, Func<A2, R>> (and a Func<R> is more like a Func<Unit, R>), so all the variants correspond to the single Func case.

Title: What is the advantage of currying?

Body:
Currying is an advantage when you don't have all of the arguments for a function. If you happen to be fully evaluating the function, then there's no significant difference.

Currying lets you avoid mentioning not-yet-needed parameters. It is more concise, and doesn't require finding a parameter name that doesn't collide with another variable in scope (which is my favorite benefit).

For example, when using functions that take functions as arguments, you'll often find yourself in situations where you need functions like "add 3 to input" or "compare input to variable v". With currying, these functions are easily written: add 3 and (== v). Without currying, you have to use lambda expressions: x => add 3 x and x => x == v. The lambda expressions are twice as long, and have a small amount of busy work related to picking a name besides x if there's already an x in scope.

A side benefit of languages based on currying is that, when writing generic code for functions, you don't end up with hundreds of variants based on the number of parameters. For example, in C#, a 'curry' method would need variants for Func<R>, Func<A, R>, Func<A1, A2, R>, Func<A1, A2, A3, R>, and so forth forever. In Haskell, the equivalent of a Func<A1, A2, R> is more like a Func<Tuple<A1, A2>, R> or a Func<A1, Func<A2, R>> (and a Func<R> is more like a Func<Unit, R>), so all the variants correspond to the single Func<A, R> case.


答: an easy one that comes to mind is addIfAbsent()

Title: addIfNotExist alternative

Body:
Is there are any standards or conventions on naming methods which add something if it not exist into another something.

For example: Store.instance().addItemIfNotExist(item)

IfNotExist is really ugly part. What workaround may be?


问:
IPv4 to IPv6. where is IPv5?
As all of us know that after IPv4 it came IPv6. How this transition happened?

I just want to know was there any IPv5 also? or there is any other logic in naming this version of IP as IPv6?

答:
"So what happened to IPv5? IPv5 was used to define an experimental real-time streaming protocol. To avoid any confusion, it was decided to not use IPv5 and name the new IP protocol IPv6. " (Cisco CCNA Exploration Courses - Accessing the WAN)

Here's a link! @ Hemant You will find there enhancements that IPv6 offers.

Title: IPv4 to IPv6. where is IPv5?

ContentLicense: CC BY-SA 4.0


答: I convert data to JSON on the server by using a series of "plug-ins" that convert standard data sets to multiple styles of JSON. This allows me to convert data to objects, array of arrays or custom formats (like that used by DataTables). My data layer doesn't have to change, I just switch out the JSON formatter when needed.</p>

Title: Server side JavaScript rendering

Body:
I have almost a 'best-practice' question that's been nagging at me for a while.

When I use JavaScript libraries and APIs such as JQGrid or Google Maps, I tend to find myself creating server side libraries to render the JavaScript for me.

For example I might have:

```<code>$map->setZoom(10);
$map->setDimensions(200,250);
</code>```

in PHP, which would internally render the relevant JS when I call $map->render();, for example.

This means I can easily generate JavaScript based on the state of my applications. I also find it easier to work with the data I already have in my controllers etc.

Is this a suitable way of using common functionality within a JavaScript library or would it be better to write JS as standard?


答:
The latency of network must be the biggest concern of web development.
So it is not wise to change the js files which cached by the browser according to user inputs .

The data and the logic comprise of the world.
The state of your application is actually the data, let the  data changes over time instructing your logic to do the job.
That is not telling you to push all the logic to clients, but push what they need.

Title: Server side JavaScript rendering


问:
Math library methods in Google's Go Programming Language
I have been programming in google Golang and have been enjoying it due to its brevity but I find it surprising that almost all its Math standard library methods are for the floating point type. Is there any particular reason why these methods do not exist for ints?</p>

答:
The short answer is that Go is a successor to C, and C's standard math library is also defined almost exclusively in terms of single- and double-precision floating point values.

The longer answer is that in a statically-typed language without polymorphism or function overloading, like Go (or C), you need to settle on a type for a function to take and return in advance, and once you're going to deal with specific types in your math library, there are a lot more interesting operations on floating point numbers than integers. To pick a few examples

the square or nth root of an integer or floating point number is usually not representable as an integer

very few interesting values of transcendental functions are representable as integers

division of floating point values requires less rounding than division of integers

Note that this is not as onerous as it might seem if your input values are integers -- an integral value can be converted to a floating point value with a simple typecast, and mostly accurately.

So that's the story for languages like Go or C.  Other languages have other options:

A dynamically typed language can provide math library functions which take or return multiple types depending on what they are called with or whether the return value is representable as an integer.

A language with function overloading can provide multiple versions of the same function, depending on the types you pass (strictly, these are multiple functions with the same name, as distinct from the dynamically typed case above)

A language with type polymorphism (such as object oriented languages with inheritance) can define a superclass "Number" with subclasses for both integers and floating point values, and then define math functions in terms of this Number class.  This approach has much of the flexibility of the dynamic language approach, while still keeping much of the strictness of the static or function-overloading approach.

Go has none of these features, however.


问:
Should my small software library avoid using other libraries?
I've just released a small Java library that offers only a few classes and methods. Since I built the project with Maven, I immediately used several third-party libraries to achieve my goals, specifically:

commons-lang3 (for some general Java stuff)

slf4j-api (for logging)

commons-io (for a tiny bit of file stuff - literally reading a file once, I think)

I don't want my library to appear bloated in the eyes  of others. Should I be trying to remove my reliance on these libraries to minimise my footprint? Any advice on what types of libraries would be best to avoid when considering using more in the future?

答:
No.

"Bloat" is a myth.  No matter how much code is in your library, if some of that code is never used it won't be paged in - it will have no impact whatsoever on either performance or memory footprint.

On the other hand, if you need that extra piece of functionality you have two choices.  You can either write it yourself and spend a lot of time and effort solving problems that others have already solved before, or you can choose to use the solution that already exists (and has been tested/debugged/etc).

That leaves us with download size and disk space footprint, and unless you're talking silly numbers, in 2013 they're two factors that should be close to the bottom of the list of things you need to worry about.


答: There's no rule that Java package names or .NET namespaces be domain names.  There isn't even a requirement that they be unique, although that's certainly a Good Idea.  I actually think you were right to use com.googlecode.oldproj, and in your shoes I wouldn't have switched to com.oldproj unless I was trying to get publicity for the new domain name.

Title: How can I avoid using my own name in the identifiers, packages, or namespaces of open sources projects I create?

Body:
I do a lot of development in my own time. These projects I work on are all just for fun and learning (so far). I commonly do Java development with Maven but I have also been known to dabble in .NET and Python. All of the projects I work on use open source licenses, although most of them are not on any public code repositories.

Java/Maven development requires me to use a unique groupId (e.g. "com.mydomain") and a unique package (directory) structure, usually containing the groupId while .NET development encourages unique namespaces in which I use similar conventions to the Java package concept. To ensure uniqueness, I usually just use one of my domain names with the parts reversed (e.g. "ca.jessewebb"); I believe this is a very common practice.

I am in the initial stages of creating a new, open source, Java/Maven project (let's call it "newproj") and I would like to put it on GitHub. My username on GitHub is "jessewebb" so this will give it a URL like: https://github.com/jessewebb/newproj. I don't want to bother registering the "newproj.com" domain name so I decided to use "ca.jessewebb" and "ca.jessewebb.newproj" as the groupId and package, respectively.

It occurred to me that the presence of my personal identity in the code and as part of the project's home (in the GitHub URL) will likely cause a potential contributor to think twice about getting involved with my project. This is a problem, I don't want it to be my project. I would prefer if I could, instead, convey the message that I do not own the project. Now, in all honesty, it really isn't that big of a deal because I doubt my projects will garner much community involvement but I also see this as even more of a reason to avoid any possibility of deterring would-be contributors.

For another example, I created a Google Code project a few years ago (let's call it "oldproj"). When I created the project, I knew I was going to host it on Google Code so I used the groupId and package name of "com.googlecode.oldproj", which is the reverse of the default domain name Google Code provides every new project. This turned out to be a not-so-great idea; a year or so later, I moved the code to a different repo and I had to rename these identifiers (well I didn't have to but...). At the time, I didn't own any domain names and I ended up buying the domain name "oldproj.com" and I used it. I liked this because it gave the project its own identity and I wasn't stamping my name on the code everywhere. I could have just as easily registered the "jessewebb.ca" domain name and used "ca.jessewebb.oldproj" as the package name but I didn't because I had the same concerns back then too.

So my question is...

How can I avoid using my own (domain) names when creating open source projects while still maintaining uniqueness of packages/namespaces?

As projects gain more momentum, it makes sense to register the domain names but it seems silly and a waste of money to do this earlier on. I realize that I don't actually have to own the domain name to use it in the code but that feels wrong and can lead to a squatter snatching it from under you in the meantime. What do other people do about this dilemma? Are there examples of popular (widely used, large community, etc.) open source projects that contain the original developer's identity as part of its own identifier(s)?


问:
How can a Right-Brainer Deal with Massive Left-Brainer Code?
I'm an artist, mostly, though I describe myself as a artist/physicist.  While I can do math, deal with  words, and the "logical" stuff considered left-brain, it's an effort and I make mistakes, whereas I do well with and most of the time think in terms of those things associated with right-brain thinking - spatial relations, holistic big-picture context, etc.  Of course all that is fuzzy, as the right-left brain theory is oversimplified and no mental activity is so simple.   Yet I do sense that I fit in fine with artists, video directors, chefs, and other non-verbal thinking, creative types, while most people in "IT" or hardcore software engineers have minds that work differently, with attention to detail, holding many details in mind at one time, and strong rational and verbal capabilities.

So here I am in a job being paid to fix fussy and obscure bugs in a massive swarm of C++ software, very heavy on OO, and any one line of code makes no sense unless I hold in mind about twenty other class and method names, relations between them, the flow of execution (very spaghetti-like) and other detail.

Besides that,  I'm also rather strongly against much of contemporary C++ and OO styles.  Those who wrote this code really drank the deep OO and Modern C++ kool-ade.  I find it actually makes code much harder to follow, much harder to decide where to fix or change something.   I don't know if this is part of the left/right differnce (or whatever you want to call it) or not.

But work on the C++ I must - people depend on me for my income.  What are tips and techniques to deal with this situation, to be as effective as possible for my employer?

答:
It doesn't sound (at least to me) like your code is particularly object-oriented, or particularly similar to "Modern C++". Rather the contrary, one of the key elements of good object orientation is encapsulation, the primary intent of which is to reduce the number of things you need to keep track of at any given time. Likewise, "very spaghetti-like ... flow of execution" sounds neither object oriented nor modern (anything).

Now, I suppose if I looked at the code you're maintaining, I might see it differently, and/or you might see my code as being similar to what you're maintaining right now -- that's a bit hard to guess. It is true that if you tried to trace through every detail of how my code works, I suppose you could see it as a rather spaghetti-like flow of control.

Just for example, I'm a lot more fond (or at least tolerant) of quite a few implicit conversions than many programmers -- I use things like proxy classes quite a bit. This means there might easily be three or four temporary objects of different types created in the course of calling a single function (and note that I'm not talking about actually executing the function, just calling it). Of course, all of those temporary objects will be destroyed again at the end of the expression containing the function call. If you count it up, you might easily have half a dozen or more separate functions invoked in calling/returning from one function that's "visibly" called in the code.

The point of doing things that way, however, is to make it easy to ignore most of the trivia involved in (for example) dealing with details like how a particular object is represented, and concentrate solely on what it really is instead. You'd only ever need to deal with most of that code if you saw a bug in that particular part. I try to avoid much of that, however, by creating classes so small and simple, that do so little, that it takes barely more than a glance to realize that it's obviously correct, so it's easy to ignore from then on.


答:
I can't remember where I've seen it, but I've seen it suggested to use a structure like this:

```<code>YourIdentifier.YourProduct.YourComponent
</code>```

YourIdentifier can be something like a domain you own, your (fairly unique) internet alias, etc etc. The component name is left off for "core" code of your product. For instance, I have a small MVC framework named BarelyMVC, so I have namespaces like these in it:

```<code>Earlz.BarelyMVC
Earlz.BarelyMVC.Authentication
Earlz.BarelyMVC.Caching
</code>```

etc etc. Your online alias in most cases is plenty unique to avoid conflicts between other developers

If you're afraid to use your own online alias, then create a "label" for yourself. It doesn't have to be formally registered as a company or anything(or even a domain). For instance, the popular Json.Net library uses the namespace Newtonsoft.Json. It's obviously based on the authors last name "newton", but I don't think anyone really cares about that. And if you do have a formal company registered, then you can of course use that. Most public APIs produced by my company for instance has namespaces beginning with PreEmptiveSolutions, the name of the company

Body:
I can't remember where I've seen it, but I've seen it suggested to use a structure like this:

YourIdentifier.YourProduct.YourComponent

YourIdentifier can be something like a domain you own, your (fairly unique) internet alias, etc etc. The component name is left off for "core" code of your product. For instance, I have a small MVC framework named BarelyMVC, so I have namespaces like these in it:

Earlz.BarelyMVC
Earlz.BarelyMVC.Authentication
Earlz.BarelyMVC.Caching

etc etc. Your online alias in most cases is plenty unique to avoid conflicts between other developers

If you're afraid to use your own online alias, then create a "label" for yourself. It doesn't have to be formally registered as a company or anything(or even a domain). For instance, the popular Json.Net library uses the namespace Newtonsoft.Json. It's obviously based on the authors last name "newton", but I don't think anyone really cares about that. And if you do have a formal company registered, then you can of course use that. Most public APIs produced by my company for instance has namespaces beginning with PreEmptiveSolutions, the name of the company


答:
C# shouldn't necessarily be avoided. I work for PreEmptive Solutions on their Dotfuscator team, though this is a fairly unbiased answer. (without a single plug :) )

C# is inherently easier to decompile into source code because it contains meta-data and most C# code must comply with a set of rules called "verifiable code". Decompilers take advantage of the adherence to these rules along with attached metadata to make decompilation much better than equivalent C++ decompilers. It's hard to get into with a thorough understanding of IL, but basically each class in your code will end up having metadata. It's how .Net prevents you from having to ship header or symbol files for someone to use an assembly/API you write. And for the verifiable code bit, it basically means that you can only use code that the .Net runtime can verify is "safe". The runtime is limited in it's static analysis capabilities, so there is a lot of code that can be verified is "safe and correct", but won't be verifiable by the runtime. Decompilers take advantage of this set of rules.

If you're shipping a product in C# and have IP you want to protect, you basically have to use an obfuscation product. It's the same in similar languages/runtimes such as Java. Obfuscation products for .Net do a variety of things:

Obfuscate control flow (turn if statements into loops with goto and reorder everything)

Inject garbage no-operation instructions to "hide" the real code

Rename metadata so it doesn't really help. (turning class names like FooBar into a)

Change how classes are structured (moving 5 methods into a single method taking all the arguments from the 5 methods)

Inject unverifiable code or metadata (though this is usually easily defeated by deobfuscators)

Encrypt strings so that they aren't just plain text

Encrypt resources such as attached configuration files, XAML pages, etc

Add tamper protection (detection that the application has been changed)

Depending on which obfuscator you use, these methods can make it so for all intents and purposes the code is a huge "black box" without diving into the IL and hand deobfuscating it(very time consuming)

C++ has the plus that obfuscation isn't nearly as important. There is no metadata so decompilers have a much harder time. However, there are still a great deal of hackers that can read x86 assembly. And C++ applications very commonly get cracked. (good) C++ obfuscators are also much harder to come by. This is because they are about as difficult to obfuscate as they are to decompile. .Net has a set of rules that obfuscators use to both read your code, and obfuscate it. C++ doesn't have these rules.

So, in summary

C# basically requires obfuscation

C++ is much harder to decompile, but obfuscation support is lacking

No matter which one you choose, it is always possible to crack. All you can do is slow it down or make it undesirable to crack due to the amount of time required

Also, as one more note. C# obfuscators which produce verifiable code basically give you an application which will run everywhere, as long as they have a new enough version of .Net. C# obfuscators which don't produce verifiable code will usually work everywhere, but they aren't guaranteed to. It's possible Microsoft would come out with some JIT optimization in the next version of .Net that will break your unverifiable obfuscated code. C++ code inherently does not usually run "everywhere", but it usually does. Obfuscated C++ code will probably work everywhere you intend to, but it's not guaranteed. Writing correct and thread-safe C++ is hard enough, much less worrying about an obfuscator screwing that up.


问:
Where and when to include assets in languages that don't care where they are declared?
I come from c++, where one declares all assets to be included at the top of a file. That is what I have been doing with php as well. Lately I have been tempted to stray from this rule: I have a script file where I put functions I use throughout my projects, sort of like a library script. There are some functions included that require assets that no other function uses, and since one can put require_once statements all throughout one's scripts, I have been tempted to include assets at the beginning of those functions, to conserve resources when the script is running. Is this kind of thing frowned upon in OOP, or is that OK? I guess while I am at it, should I not be doing this at all because there is a purerer OOP approach to the kind of library scripts I have been creating?</p>

答:
The best answer is that you should follow the conventions / recommendation's set out in the language's style guides.

For instance, Sun's Java Style Guide recommends that you declare static variables, then instance variables, then constructors and then methods; see http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141855.html#1852.

(This order probably makes sense for other OO languages too ... if there are no commonly used style guides specific to the language.)


问:
Should Controller know about View & Model? or vice versa?
I'm conceptually trying to understand if I should be doing this:

```<code>item = Model()
screen = View()
brain = Controller(item, screen)
</code>```

or this..

```<code>brain = Controller()
item = Model(brain)
screen = View(brain)
</code>```

or this..

```<code>class Controller():
    def __init__(self):
        item = Model(self)
        screen = View(self)
</code>```

or something else entirely?

答:
To me, the first option makes sense. The job of the Controller is to co-ordinate between the view and the model. From that point of view, it makes sense for the controller to be the one that controls references to the view and model.

You can't really have a controller without a Model and a View, however it makes a lot more sense to just have a View or just have a Model (for example, in unit testing). That's why you want to pass in those dependencies into the Controller, and not the other two.


问:
Should I create interfaces for data transfer objects?
Is it a good idea or a bad idea to create an interface for data transfer objects?  Presuming that the object is usually mutable.

Though my example is in Java, it should be applicable to any other language that has similar concepts.

```<code>interface DataTransferObject  {
    String getName();
    void setName(String name);
}

class RealDataTransferObject  implements DataTransferObject {

    String name;
    String getName() {
        return name;
    }
    void setName(String name) {
        this.name = name;
    }
}
</code>```

Of course, this is a simplified example, in real life there may be more fields.

答: If you want this object to have some sort of fields validation in future, you should incapsulate them on early stages.</p>


问:
Design pattern for polymorphic behaviour while allowing library separation
Let's say I have a hierarchy of Item classes: Rectangle, Circle, Triangle. I want to be able to draw them, so my first possibility is add a virtual Draw() method to each:

```<code>class Item {
public:
   virtual ~Item();
   virtual void Draw() =0;
};
</code>```

However, I want to split the drawing functionality to a separate Draw library while the Core library contains only the basic representations. There's a couple of possibilities I can think of:

1 - A DrawManager that takes a list of Items and has to use dynamic_cast<> to work out what to do:

```<code>class DrawManager {
  void draw(ItemList& items) {
    FOREACH(Item* item, items) {
       if (dynamic_cast<Rectangle*>(item)) {
          drawRectangle();
       } else if (dynamic_cast<Circle*>(item)) {
          drawCircle();
       } ....
    }
  }
};
</code>```

This isn't ideal as it relies on RTTI and forces one class to be aware of all items in the hierarchy.

2 - The other approach is to defer drawing responsibility to an ItemDrawer hierarchy (RectangleDrawer, etc):

```<code>class Item {
   virtual Drawer* GetDrawer() =0;
}

class Rectangle : public Item {
public:
   virtual Drawer* GetDrawer() {return new RectangleDrawer(this); }
}
</code>```

This achieves the separation of concerns between the base representation of the Items and the code for drawing. The problem though is that the Item classes are dependent on the drawing classes.

How can I separate out this drawing code into a separate library? Is the solution for the Items to return a factory class of some description? However, how can this be defined so that the Core library isn't dependent on the Draw library?

答:
Have a look at Value Semantics and Concepts-based Polymorphism.

This work has changed how I look at polymorphism. We have used this system to great affect in repeated situations.


问:
My most cherished dream project seems to resemble a product that already exists. What shall I do?
I guess this is more of a "comfort seeking" question than legality one.

You see, for the past couple of months I have been brainstorming and developing a product, all by myself. I was planning to release it under some kind of free license. While I know no idea is ever a unique one, I was quite happy to note that the way I had visualized my software, in its form and purpose, was one of its kind, albeit bits and pieces resembling others. That private project was quite cherished one.

Now I find there is a product, at least a decade old, that is so close to mine that mine looks plagiarized. While with the rest of them I had a 8:2 in my favor, feature wise, with this product it seems transposed, including the philosophy. I admit I can vaguely recall hearing the name of it but never thought of reading about it - the name didn't seem to invoke interest etc - until now. I read about it and now I am distraught and agonized.

There is no risk of any legal action as that software is in "free" domain and mine is still a private project, and I don't know if it will be ever make any money from any buyer which will then lead to trouble, but that is not the point of the question.

The point is how to stay focused and enthusiastic as before? I have about a month of work pending, mainly programming and complete testing, and this has completely left me drained. I am in a fetal position. I am telling myself about Newton-Leibniz, Faraday-Henry kind of independent activities with similar to same results but that isn't helping. I don't want this to spill over to my regular life and work life.

I can sense two issues that are pricking me. (1) I wanted praise for my creativity. (2) I was harboring a small desire of a possible chance of making good money by attracting a buyer.

This might be a casual and almost an inconsequential problem for the citizens of the business world, but I am from a different world.

Help.

答:
Is the other project "open source"? If so, you can join that community and improve it. If not, you can make yours open source and try to attract similar minded people.

As you can tell I am not from the business world either.