问:
Why isn't there a typeclass for functions?
In a learning problem I've been messing around with, I realised I needed a typeclass for functions with operations for applying, composing etc. Reasons...

It can be convenient to treat a representation of a function as if it were the function itself, so that applying the function implicitly uses an interpreter, and composing functions derives a new description.

Once you have a typeclass for functions, you can have derived typeclasses for special kinds of functions - in my case, I want invertible functions.

For example, functions that apply integer offsets could be represented by an ADT containing an integer. Applying those functions just means adding the integer. Composition is implemented by adding the wrapped integers. The inverse function has the integer negated. The identity function wraps zero. The constant function cannot be provided because there's no suitable representation for it.

Of course it doesn't need to spell things as if it the values were genuine Haskell functions, but once I had the idea, I thought a library like that must already exist and maybe even using the standard spellings. But I can't find such a typeclass in the Haskell library.

I found the Data.Function module, but there's no typeclass - just some common functions that are also available from the Prelude.

So - why isn't there a typeclass for functions? Is it "just because there isn't" or "because it's not so useful as you think"? Or maybe there's a fundamental problem with the idea?

The biggest possible problem I've thought of so far is that function application on actual functions would probably have to be special-cased by the compiler to avoid a looping problem - in order to apply this function I need to apply the function application function, and to do that I need to call the function application function, and to do that...

More Clues

Example code to show what I'm aiming for...

```<code>{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}

--  In my first version, Doable only had the one argument f. This version
--  seemed to be needed to support the UndoableOffset type.
--
--  It seems to work, but it also seems strange. In particular,
--  the composition function - a and b are in the class, but c isn't,
--  yet there's nothing special about c compared with a and b.
class Doable f a b where
  fwdApply :: f a b -> a -> b
  compDoable :: f b c -> f a b -> f a c

--  In the first version, I only needed a constraint for
--  Doable f a b, but either version makes sense.
class (Doable f a b, Doable f b a) => Undoable f a b where
  bwd      :: f a b -> f b a

  bwdApply :: f a b -> b -> a
  bwdApply f b = fwdApply (bwd f) b

--  Original ADT - just making sure I could wrap a pair of functions
--  and there were no really daft mistakes.
data UndoableFn a b = UFN { getFwd :: a -> b, getBwd :: b -> a }

instance Doable UndoableFn a b where
  fwdApply = getFwd
  compDoable f g = UFN ((getFwd f) . (getFwd g)) ((getBwd g) . (getBwd f))

instance Undoable UndoableFn a b where
  bwd f    = UFN (getBwd f) (getFwd f)
  bwdApply = getBwd

--  Making this one work led to all the extensions. This representation
--  can only represent certain functions. I seem to need the typeclass
--  arguments, but also to need to restrict which cases can happen, hence
--  the GADT. A GADT with only one constructor still seems odd. Perhaps
--  surprisingly, this type isn't just a toy (except that the whole thing's
--  a toy really) - it's one real case I need for the exercise. Still a
--  simple special case though.
data UndoableOffset a b where
  UOFF :: Int -> UndoableOffset Int Int

instance Doable UndoableOffset Int Int where
  fwdApply (UOFF x) y = y+x
  compDoable (UOFF x) (UOFF y) = UOFF (x+y)

instance Undoable UndoableOffset Int Int where
  bwdApply (UOFF x) y = y-x
  bwd (UOFF x) = UOFF (-x)

--  Some value-constructing functions
--  (-x) isn't shorthand for subtraction - whoops.
undoableAdd :: Int -> UndoableFn Int Int
undoableAdd x = UFN (+x) (\y -> y-x)

undoableMul :: Int -> UndoableFn Int Int
undoableMul x = UFN (*x) (`div` x)

--  With UndoableFn, it's possible to define an invertible function
--  that isn't invertible - to break the laws. To prevent that, need
--  the UFN constructor to be private (and all public ops to preserve
--  the laws). undoableMul is already not always invertible.
validate :: Undoable f a b => Eq a => f a b -> a -> Bool
validate f x = (bwdApply f (fwdApply f x)) == x

--  Validating a multiply-by-zero invertible function shows the flaw
--  in the validate-function plan. Must try harder.
main = do putStrLn . show $ validate (undoableAdd 3) 5
          putStrLn . show $ validate (undoableMul 3) 5
          --putStrLn . show $ validate (undoableMul 0) 5
          fb1 <- return $ UOFF 5
          fb2 <- return $ UOFF 7
          fb3 <- return $ compDoable fb1 fb2
          putStrLn $ "fwdApply fb1  3 = " ++ (show $ fwdApply fb1  3)
          putStrLn $ "bwdApply fb1  8 = " ++ (show $ bwdApply fb1  8)
          putStrLn $ "fwdApply fb3  2 = " ++ (show $ fwdApply fb3  2)
          putStrLn $ "bwdApply fb3 14 = " ++ (show $ bwdApply fb3 14)
</code>```

The application involves a kind of unification where unified values aren't equal, but are related via those invertible functions - Prolog-style logic but with a = f(b) constraints rather than a = b. Most of the composition will result from optimizing a union-find structure. The need for inverses should be obvious.

If no item in a unified set has an exact value, then a particular item can only be quantified relative to another item in that unified set. That's why I don't want to use "real" functions - computing those relative values. I could drop the whole function aspect and just have absolute and relative quantities - I probably only need numbers/vectors and (+) - but my inner architecture astronaut wants his fun.

The only way I break the links apart again is via backtracking, and everything is pure - union-find will be done using keys into an IntMap as "pointers". I have simple union-find working, but as I haven't added the invertible functions yet, there's no point listing it here.

Reasons I can't use Applicative, Monad, Arrow etc

The main operations I need the function abstraction class to provide are application and composition. That sounds familiar - e.g. the Applicative (<*>), Monad (>>=) and Arrow (>>>) are all composition functions. However, the types that implement the function abstraction in my case will contain some data structure that represents a function, but which isn't (and can't contain) a function, and which can only represent some limited set of functions.

As I mentioned in the explanation of the code, sometimes I can only quantify one item relative to another because no item in a "unified" cluster has an exact value. I want to be able to derive a representation of that function, which in general will be the composition of several provided functions (walking up to a common ancestor in the union/find tree) and of several inverse functions (walking back down to the other item).

Simple case - where the original "functions" are limited to integer-offset "functions", I want the composed result as an integer-offset "function" - add the component offsets. That's a big part of why the composition function needs to be in the class as well as the application function.

This means I cannot provide the operations pure, return or arr for my types, so I can't use Applicative, Monad or Arrow.

This isn't a failure of those types - it's a mismatch of abstractions. The abstraction I want is of a simple pure function. There's no side-effecting, for example, and no need to build a convenient notation for sequencing and composing the functions other than an equivalent of the standard (.) that applies to all functions.

I could instance Category. I'm confident that all my functiony-things will be able to provide an identity, though I probably don't need it. But as Category doesn't support application, I'd still need a derived class anyway to add that operation.

答:
In addition to the mentioned Category, Arrow, and Applicative:

I've also discovered Data.Lambda by Conal Elliott:

Some function-like classes, having lambda-like construction

Looks interesting, of course, but difficult to understand without examples...

Examples

Examples can be found in the wiki-page about tangible values (TV) who seem to be one of the things that caused the creation of TypeCompose library; see Inputs and function-valued outputs.

The TV library's idea is to display Haskell values (including functions) in a tangible manner.

To follow the StackOverflow rule about not posting bare lonks, I copy some bits below which should give the idea of these things:

The first example reads:

```<code>apples, bananas :: CInput Int
apples  = iTitle "apples"  defaultIn
bananas = iTitle "bananas" defaultIn

shoppingO :: COutput (Int -> Int -> Int)
shoppingO = oTitle "shopping list" $
            oLambda apples (oLambda bananas total)

shopping :: CTV (Int -> Int -> Int)
shopping = tv shoppingO (+)
</code>```

which gives when run as runIO shopping (see there for more comments, GUIs, and more examples):

```<code>shopping list: apples: 8
bananas: 5
total: 13
</code>```

Body:
In addition to the mentioned Category, Arrow, and Applicative:

I've also discovered Data.Lambda by Conal Elliott:

Some function-like classes, having lambda-like construction

Looks interesting, of course, but difficult to understand without examples...

Examples

Examples can be found in the wiki-page about tangible values (TV) who seem to be one of the things that caused the creation of TypeCompose library; see Inputs and function-valued outputs.

The TV library's idea is to display Haskell values (including functions) in a tangible manner.

To follow the StackOverflow rule about not posting bare lonks, I copy some bits below which should give the idea of these things:

The first example reads:

apples, bananas :: CInput Int
apples  = iTitle "apples"  defaultIn
bananas = iTitle "bananas" defaultIn

shoppingO :: COutput (Int -> Int -> Int)
shoppingO = oTitle "shopping list" $
            oLambda apples (oLambda bananas total)

shopping :: CTV (Int -> Int -> Int)
shopping = tv shoppingO (+)

which gives when run as runIO shopping (see there for more comments, GUIs, and more examples):

shopping list: apples: 8
bananas: 5
total: 13


问:
floating-point number stored in float variable has other value
I'm reading a book about C programming By "King.K.N" and I'm reading the following statement:

If we store 0.1 in a float variable, we may later find that the variable has a value such as 0.0999999999999999987

But I can't understand why float type variable may have different value?

答:
You try to store decimal 0.1 in a float variable. When we talk about float in C (and in most other languages), numbers according to IEEE Standard for Floating-Point Arithmetic (IEEE 754) are meant.

Float numbers are stored in base 2, and 1/10 cannot be converted to a binary fraction in a lossless way.

Think of how you try to store 1/3 in base 10: You end up with 0.33333. But 3 * 0.33333 is not equal to 1, but to 0.99999.

For more details, read What Every Computer Scientist Should Know About Floating-Point Arithmetic

ContentLicense: CC BY-SA 3.0


问:
shared or raw pointer c++
I am developing a noSQL database and currently moving the code from C to C++.

It have class Pair, which contains a raw pointer to a memory blob.

```<code>class Pair {
  Blob* blob;
  ...
};
</code>```

Then if you add this Pair to the List class, the List class stores this raw pointer internally, without copying. In order not to leak memory, the List notifies the Pair not to delete the raw pointer.

```<code>class Pair {
  Blob* _blob;
  bool _owns_blob;

public:
  Pair(Blob* blob, bool owns_blob = true)
    : _blob(blob), _owns_blob(owns_blob) {}
  ~Pair() { if (_owns_blob) delete _blob; }
  ...
  Blob* blob() { return _blob; }
  void disown() { _owns_blob = false; }
};

void List::put(Pair& p) {
  store_blob(p.blob());
  p.disown();
}
</code>```

Because of this notification, I can not use a method signature like this:

```<code>List.put(const Pair &p)
</code>```

and I will need to pass by value or by non-const reference.

Later if you request the data, the program creates a new Pair and includes the raw pointer inside, and also instructs the Pair not to delete the pointer:

```<code>Pair List::get(...) {
  return Pair(get_blob(), false);
}
</code>```

Would this model benefit from shared pointers? How would this affect the speed and memory consumption?

答:
Would this model benefit from shared pointers?

It looks like you hold the pointers and take ownership of them. It also seemsn that client code doesn't share ownership. At this point (heh punny!), you would benefit from implementing this in terms of a std::unique_ptr, and exposing either a custom safe wrapper around a pointer, or a Blob* const to client code.

How would this [using std::shared_ptr] affect the speed and memory consumption?

Regarding the speed, we cannot say, unless we know all your algorithms, and even then, we may not be able to say until you measure.

With shared pointers, the speed will be affected, but nobody can tell if this is signifficant until you measure (the change will decrease performance, but if your changes are not on the critical execution path, such decreases would be rendered insignificant by other performance bottlenecks).

Regarding memory consumption, a shared pointer has a foot print ~ three times as big as a raw pointer:
- the data pointer itself
- the reference count
- the pointer to the internal object holding the two values above.

This will be signifficant if you store many many (many many many) pointers, and insignifficant otherwise.

Title: shared or raw pointer c++


问:
Best practices for a daemon that forks and becomes user
I want to write a small daemon in python under Linux that accepts connections and authenticates the user (details for this don't matter) and then forks a child for the connection and becomes the user. I will probably even want to start a whole new python program for dealing with the users connection from then on (passing the socket as stdin/stdout?).

Now my question is: What are the best practices for the forking and becoming the user? My question is about how to handle login records (utmp, wtmp), pam, and whatever other things the child should do when becoming the user. And all of that in python.

答:
The basic stuff has to do with closing unneeded file handles, checking over signal handling and setting the proper user and group, as well as the daemonization process itself (attaching to init). On Linux systems or where possible in addition to setting uid and gid, there's setting a session id so that the process might be more easily found.

There is a python daemonize module that I'd consult for what things to consider, if not use the module itself. (I've not used it, so I don't know firsthand its usefulness).


问:
How do I design a subclass whose method contradicts its superclass?
How do I design a subclass whose method contradicts its superclass? Let's say we have this example:

```<code># Example 1

class Scissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  def right_handed?
    false
  end
end
</code>```

Let's assume that the inheritance is necessary in this example e.g. that there might be other methods aside from right_handed? that are being inherited.

So a LeftHandedScissor is a Scissor. Its method right_handed? matches the signature and return value type of its superclass's method. However, the subclass method contradicts the return value of the superclass method.

This bothers me because it looks like a logical contradiction:

All scissors are right-handed.

A left-handed scissor is a scissor.

Therefore, a left-handed scissor is right-handed.

I considered introducing an AbstractScissor to avoid this contradiction:

```<code># Example 2

class AbstractScissor
  def right_handed?
    raise NotImplementedError
  end
end

class RightHandedScissor < AbstractScissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < AbstractScissor
  def right_handed?
    false
  end
end
</code>```

My colleague says the downside to this solution is that it's more verbose. Aside from adding an extra class, it requires us to call scissors "right-handed scissors", which no one does in the real world.

This leads me to my last solution:

```<code># Example 3

class AbstractScissor
  def right_handed?
    raise NotImplementedError
  end
end

class Scissor < AbstractScissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < AbstractScissor
  def right_handed?
    false
  end
end
</code>```

It's nearly the same as example 2 but I just renamed RightHandedScissor as Scissor. There's a chance that someone might assume LeftHandedScissor is a subclass of Scissor based solely on the class names, but at least the code makes it obvious that that's not the case.

Any other ideas?

答:
This bothers me because it looks like a logical contradiction:

All scissors are right-handed.

Incorrect at this point. You've defined scissors as all having handedness, and that this defaults to right-handed if not overridden. You have not said that all scissors are right-handed, that would require overriding being prohibited (as can be done in some languages, and not in others).

Remove that false premise, and the contradiction is no longer there.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答: Well, I thought Microsoft is/was considered evil and now recently Oracle is the most evil thing in the world.</p>

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?


问:
Is method overriding always a violation of Liskov Substitution Principle?
Overriding a method originally defined in the super class, by definition means this method will do different things when invoked on an object of the base class or an object of the subclass.

So does this mean that overriding methods always means violating LSP? Or are there cases when it doesn't?

答:
The Liskov Substitution Principle only says that subclasses should not violate provable properties of the supertype. The provable properties are basically the type signatures of members. So if a method on a superclass is declared to return an integer, then it shouldn't be overwritten in subclass to return a string.

Type systems in modern statically-typed OO languages generally prevent this from happening, so as an ordinary developer of say C# code you shouldn't be too worried about breaking the LSP (although I believe there are some weaknesses in the type system regarding Arrays which allows you to break LSP).

The principle is often understood more broadly (and vaguely) that subclasses should not "break expectations", which definitely a good design principle, but not really what the LSP says.


问:
Programming to an Interface and Interface Segregation in the Context of a User Class
I try to program to an interface whenever possible, but its not clear to me how I could apply it to a model as broad as a user. Which can hold many disparate fields (name, age, phone number, ssn, etc.) or be composed of many modules.

I could design a general purpose library of functionality for use across applications, that would take in an ICallable to make a phone call or INameable to display a name to the console. But in the end the user class (how the data is accessed and/or stored) would be unique to an application and its needs.

If I try to design the user and consumers in the library (stated above) to communicate by interface, I get an "interface soup" (or something "hydra-esque") on the user class. Where it feels like I'm extending an interface for almost every attribute or module.

```<code>public class Employee : INameable, ICallable, IAgeable, IPayable ...
</code>```

Is this particularly wrong? Am I taking interface use too far by completely avoiding the injection of concrete classes into the consumer (and preventing more general use)?

Whats a better approach to this problem?

答: I've also had concrete classes implement a handful of interfaces, but the classes have been mediators that delegate their behavior to single-responsibility classes that each satisfy a single interface.  The mediation class itself has little behavior outside of determining how the individual modules will interact and be utilized.  That mediation becomes its one responsibility, so SRP is preserved.</p>


答:
Congratulations, you just have discovered how the violation of Liskov Substitution Principle looks like, as the very first commenter politely pointed you at.

To answer exactly to your question: according to the aforementioned principle, you don't design a subclass whose method contradicts its superclass. Reasons for this are explained in the literature about LSP, Robert Martin, for example, talks quite a lot about it his learning videos.

To address your specific problem with logical contradictions: classes in your application do not correspond to real-world objects, and do not need to. You can read and hear about this from quite a lot of experienced speakers, J. B. Rainsberger, for example.

Body:
How do I design a subclass whose method contradicts its superclass? Let's say we have this example:

```<code># Example 1

class Scissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  def right_handed?
    false
  end
end
</code>```

Let's assume that the inheritance is necessary in this example e.g. that there might be other methods aside from right_handed? that are being inherited.

So a LeftHandedScissor is a Scissor. Its method right_handed? matches the signature and return value type of its superclass's method. However, the subclass method contradicts the return value of the superclass method.

This bothers me because it looks like a logical contradiction:

All scissors are right-handed.

A left-handed scissor is a scissor.

Therefore, a left-handed scissor is right-handed.

I considered introducing an AbstractScissor to avoid this contradiction:

```<code># Example 2

class AbstractScissor
  def right_handed?
    raise NotImplementedError
  end
end

class RightHandedScissor < AbstractScissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < AbstractScissor
  def right_handed?
    false
  end
end
</code>```

My colleague says the downside to this solution is that it's more verbose. Aside from adding an extra class, it requires us to call scissors "right-handed scissors", which no one does in the real world.

This leads me to my last solution:

```<code># Example 3

class AbstractScissor
  def right_handed?
    raise NotImplementedError
  end
end

class Scissor < AbstractScissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < AbstractScissor
  def right_handed?
    false
  end
end
</code>```

It's nearly the same as example 2 but I just renamed RightHandedScissor as Scissor. There's a chance that someone might assume LeftHandedScissor is a subclass of Scissor based solely on the class names, but at least the code makes it obvious that that's not the case.

Any other ideas?


答:
Summary: The design without the abstract class will be only be acceptable if it is carefully documented to distinguish its abstract and concrete behaviours.

The Liskov Substitution Principle is generally regarded as a "good thing".  By the LSP, I mean that if type S is a subtype of type T, then objects of type S should behave as objects of type T are expected to behave.

You can not follow this principle unless the expectations for behaviour are made clear.  This set of expectations is the so called "contract" of the class. In most languages it is expressed by a combination of signature and documentation.

Therefore, whether your first design is correct depends on the contracts.

Incorrect:

```<code>class Scissor
  # Returns true because all scissors are right-handed.
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  # Returns false
  def right_handed?
    false
  end
end
</code>```

Acceptable:

```<code>class Scissor
  # Returns true for right-handed scissors but false for left-handed ones.
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  # Returns false
  def right_handed?
    false
  end
end
</code>```

The code is the same. Whether the design is sensible (i.e. follows the LSP) or not depends on the contracts.

Now it is clear that, if you only know x.kind_of Scissors, then x.right_handed? might return either true or false.

But what about the true? Should that be documented?  Yes.  A class that can be extended needs to be documented twice. It needs documentation of its abstract behaviour, which is the behaviour we can expect from all its instance (direct or indirect), and it needs documentation of its concrete behaviour, which is the behaviour that its direct instances will have, i.e., the behaviour as implemented at this level of the inheritance hierarchy and which is inherited if not overridden.

Even better:

```<code>class Scissor
  # Abstract behaviour: Returns true for right-handed scissors but false for left-handed ones.
  # Concrete behaviour: Returns true.
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  # Abstract and concrete behaviour: Returns false
  def right_handed?
    false
  end
end
</code>```

Now it is clear also --from the documentation alone-- that, if you know s instance_of Scissors, then x.right_handed? will return true.

Often people don't bother to document the concrete behaviour, since, assuming there are no bugs, it can often be reverse engineered from the code.

The same is not true of the abstract behaviour. Unless it is documented, it can not be recovered from the code. It is left to future programmers to guess what your intentions were. Implementors of client code must guess at what they can assume about objects that are indirect instances of the class. Implementors of subclasses must guess at what is and what is not reasonable override.

All that said, I prefer your solution with the abstract class. I consider it better style.  But this is only a matter of taste.

Bottom line: The design without the abstract class will be only be acceptable if it is carefully documented to distinguish its abstract and concrete behaviours.

Title: How do I design a subclass whose method contradicts its superclass?

Body:
Summary: The design without the abstract class will be only be acceptable if it is carefully documented to distinguish its abstract and concrete behaviours.

The Liskov Substitution Principle is generally regarded as a "good thing".  By the LSP, I mean that if type S is a subtype of type T, then objects of type S should behave as objects of type T are expected to behave.

You can not follow this principle unless the expectations for behaviour are made clear.  This set of expectations is the so called "contract" of the class. In most languages it is expressed by a combination of signature and documentation.

Therefore, whether your first design is correct depends on the contracts.

Incorrect:

class Scissor
  # Returns true because all scissors are right-handed.
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  # Returns false
  def right_handed?
    false
  end
end

Acceptable:

class Scissor
  # Returns true for right-handed scissors but false for left-handed ones.
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  # Returns false
  def right_handed?
    false
  end
end

The code is the same. Whether the design is sensible (i.e. follows the LSP) or not depends on the contracts.

Now it is clear that, if you only know x.kind_of Scissors, then x.right_handed? might return either true or false.

But what about the true? Should that be documented?  Yes.  A class that can be extended needs to be documented twice. It needs documentation of its abstract behaviour, which is the behaviour we can expect from all its instance (direct or indirect), and it needs documentation of its concrete behaviour, which is the behaviour that its direct instances will have, i.e., the behaviour as implemented at this level of the inheritance hierarchy and which is inherited if not overridden.

Even better:

class Scissor
  # Abstract behaviour: Returns true for right-handed scissors but false for left-handed ones.
  # Concrete behaviour: Returns true.
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  # Abstract and concrete behaviour: Returns false
  def right_handed?
    false
  end
end

Now it is clear also --from the documentation alone-- that, if you know s instance_of Scissors, then x.right_handed? will return true.

Often people don't bother to document the concrete behaviour, since, assuming there are no bugs, it can often be reverse engineered from the code.

The same is not true of the abstract behaviour. Unless it is documented, it can not be recovered from the code. It is left to future programmers to guess what your intentions were. Implementors of client code must guess at what they can assume about objects that are indirect instances of the class. Implementors of subclasses must guess at what is and what is not reasonable override.

All that said, I prefer your solution with the abstract class. I consider it better style.  But this is only a matter of taste.

Bottom line: The design without the abstract class will be only be acceptable if it is carefully documented to distinguish its abstract and concrete behaviours.


答:
As an example, if you have a class with instances representing a user interface element, and that class has a "draw" method, then the "draw" method specification will not say exactly what will be drawn. It will instead say "the user interface element will be drawn appropriately to inform the user about all the state of the user interface element that is important to the user, in an intuitive and nice looking way". If you subclass that user interface element, the subclass draw method should and likely will act exactly according to the spec.

As a general principle, if the Liskov Substitution Principle made it impossible to subclass, that would be pretty a pretty stupid, and pretty stupid principles don't get names and Wikipedia entries and are quickly forgotten :-)

(BTW. It is an art that is too often forgotten to write a proper spec for a method that is supposed to be overridden in a subclass, because any existing behaviours do not describe the spec, only a special case of it).

Title: Is method overriding always a violation of Liskov Substitution Principle?

Body:
Overriding a method originally defined in the super class, by definition means this method will do different things when invoked on an object of the base class or an object of the subclass.

So does this mean that overriding methods always means violating LSP? Or are there cases when it doesn't?


问:
What are the advantages of build scripts?
For most of my programming career, I've used the "build/compile/run" command in whatever IDE I'm working with to produce a runnable program. This is one button, pretty easy. As I learn more about different languages and frameworks, though, I see more and more talk of "build scripts" (ANT, Maven, Gradle, etc.) to get a project running. My understanding of these is that they are instructions to the compiler/linker/magical-program-maker that specify configuration details - minutiae.

I remember writing makefiles back in school, but I didn't see any special advantage then (we only used them when writing in a Unix terminal, where an IDE with it's handy "build" button wasn't present). Beyond that, I've seen other questions on here that discuss how build scripts can do more than just create your program - they can run unit tests as well as secure resources regardless of the host machine.

I can't shake the feeling that build scripts are important to understand as a developer, but I'd like a meaningful explanation; why should I use/write build scripts?

Responsibilities of Build Script and Build Server discusses the role it plays within a broader scope. I'm looking for specific advantages offered by a build script versus an IDE's "build/run" command or similarly simple methods.

答:
How else would you do it?
The only other way is to specify one long command line command.

Another reason is that makefiles allow incremental compilation, which speeds up compile time a lot.

Makefiles can also make a build process cross-platform.  CMake generates different build scripts based on the platform.

Edit:

With an IDE, you are tied down to a particular way of doing things.  Many people use vim or emacs even though they do not have many IDE-like features.  They do it because they want the power these editors provide.  Build scripts are necessary for those not using an IDE.

Even for those using an IDE, you might want to really know what is going on, so the build script offers you the low down details of implementation that a GUI approach doesn't have.

IDE's themselves use often build scripts internally too; the run button is just another way of running the make command.


答:
The only thing 'evil' is thinking that certain programming things are 'evil'.  Various approaches - use this technique, dont use that statement, use this methodology, dont use that language, use this 'best practice', etc - are opinions.

Unfortunately, too many developers mistake opinions for objective truth.

I cringe every time I see a question on here such as 'why is [x] considered evil?'.

Title: Is anything in programming truly evil?

Body:
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...


答:
```<code>make
</code>```

is a lot easier to remember and type than

```<code>gcc -o myapp -I/include/this/dir -I/include/here/as/well -I/dont/forget/this/one src/myapp.c src/myapp.h src/things/*.c src/things/*.h
</code>```

And projects can have very complex compilation commands. A build script also has the ability to only recompile the things that changed. If you want to do a clean build,

```<code>make clean
</code>```

is easier and more reliable once set up properly than trying to remember each and every place an intermediate file may have been produced.

Of course, if you use an IDE, clicking a build or clean button easy, too. However, it's much more difficult to automate moving the cursor to a specific place on the screen, especially when that place may move if the window moves, than it is to automate a simple text command.

Title: What are the advantages of build scripts?

Body:
For most of my programming career, I've used the "build/compile/run" command in whatever IDE I'm working with to produce a runnable program. This is one button, pretty easy. As I learn more about different languages and frameworks, though, I see more and more talk of "build scripts" (ANT, Maven, Gradle, etc.) to get a project running. My understanding of these is that they are instructions to the compiler/linker/magical-program-maker that specify configuration details - minutiae.

I remember writing makefiles back in school, but I didn't see any special advantage then (we only used them when writing in a Unix terminal, where an IDE with it's handy "build" button wasn't present). Beyond that, I've seen other questions on here that discuss how build scripts can do more than just create your program - they can run unit tests as well as secure resources regardless of the host machine.

I can't shake the feeling that build scripts are important to understand as a developer, but I'd like a meaningful explanation; why should I use/write build scripts?

Responsibilities of Build Script and Build Server discusses the role it plays within a broader scope. I'm looking for specific advantages offered by a build script versus an IDE's "build/run" command or similarly simple methods.

Body:
make

is a lot easier to remember and type than

gcc -o myapp -I/include/this/dir -I/include/here/as/well -I/dont/forget/this/one src/myapp.c src/myapp.h src/things/*.c src/things/*.h

And projects can have very complex compilation commands. A build script also has the ability to only recompile the things that changed. If you want to do a clean build,

make clean

is easier and more reliable once set up properly than trying to remember each and every place an intermediate file may have been produced.

Of course, if you use an IDE, clicking a build or clean button easy, too. However, it's much more difficult to automate moving the cursor to a specific place on the screen, especially when that place may move if the window moves, than it is to automate a simple text command.


答:
Many IDEs simply package up the commands used to build something and then generate a script and call it!

For example, in Visual Studio, you can see the command-line parameters for a C++ compile in the 'command line' box. If you look closely at the build output you'll see the temporary file that contains the build script that was used to run the compile.

Nowadays, it's all MSBuild, but that is still run directly by the IDE.

So the reason you use the command line is that you are going straight to the source and skipping the middle man, a middleman who might have been updated or require a heap of dependencies that you just don't want or need on a headless server that acts as your continuous integration (CI) server.

In addition, your scripts do more than the usual developer-oriented steps they're designed for. For example, after a build, you may want your binaries packaged and copied to a special location, or an installer package created, or a documentation tool run on them. Many different tasks are performed by a CI server that are pointless on a developer machine, so whilst you could create a IDE project that performed all these steps you'd then have to maintain two of them - a project for developers and another for builds. Some build tasks (static analysis for example) can take a long time that you wouldn't want for developer projects.

In short though, it's just easier - create a script to do all the things you want and it's quick and simple to kick that off on the command line or a build server configuration.


答:
Like code, a build script is executed by the computer.  Computers are exceptionally good at following a set of instructions.  In fact, (outside of self-modifying code), computers will execute the same sequence of instructions exactly the same way, given the same input.  This delivers a level of consistency that, well, only a computer can match.

By contrast, us water filled fleshbags are just downright despicable when it comes to following steps.  That pesky analytical brain has a tendency to question everything it comes across.  "Oh...I don't need to that", or "Do I really to use this flag? Eh...I'll just ignore it."  In addition, we have a tendency to get complacent.  Once we've done something a few times, we start believing that we know the instructions, and don't have to look at the instruction sheet.

From "The Pragmatic Programmer":

In addition, we want to ensure consistency and repeatability on the project. Manual procedures leave consistency up to change; repeatability isn't guaranteed, especially if aspects of the procedure are open to interpretation by different people.

In addition, we are HILARIOUSLY sluggish in executing instructions (compared to a computer).  On a large project, with hundreds of files and configurations, it would take years to manually execute all the steps in a build process.

I'll give you a real world example.  I was working some embedded software, where most of the code was shared across a few different hardware platforms.  Each platform had different hardware, but most of the software was the same.  But there were little pieces that were specific to each hardware.  Ideally, the common pieces would be placed in a library and linked into each version. However, the common pieces couldn't be compiled into a shared library.  It had to be compiled with every different configuration.

At first, I manually compiled each configuration.  It only took a few seconds to switch between configurations, and wasn't that big of a pain.  Towards the end of the project, a critical defect was discovered in the shared portion of code, where a device would essentially take over the communication bus.  This was BAD! Really bad.  I found the bug in the code, fixed it, and recompiled every version.  Except one.  During the build process, I got distracted, and forgot one.  The binaries got released, the machine was built, and a day later I get a phone call saying the machine stopped responding.  I check it out, and discovered a device had locked the bus.  "But I fixed that bug!".

I may have fixed it, but it never found its way onto that one board.  Why?  Because I didn't have an automated build process that built every single version with 1 click.


答:
Automation.

When you are developing, only in the most simple projects will the default "build" button do everything you need it to do; you may need to create WS out of APIs, generate docs, link with external resources, deploy the changes to a server, etc. Some IDEs allow you to customize the build process by adding extra steps or builders, but that only means that you are generating your build script through the IDE commodities.

But developing a system is not only writing code. There are multiple steps involved. An IDE independent script can be executed automatically, meaning that:

When you commit a change to version control, a new build can be launched automatically by the server. It will ensure that you have not forgot to commit anything needed for the build.

Similarly, after the build is done, tests can automatically be run to see if you broke something.

Now the rest of the organization (QA, sysadmins) has a built product that

a) is perfectly reproducible just from the control version.

b) is common to all of them.

Even when I have been working as a one man team I have used scripts for that purpose; when I had developed the fix I would commit to SVN, export the SVN back in another directory and use the build script to generate the solution, which would go then to Preproduction systems and later to Production. If a few weeks later (with my local codebase already changed) someone complained of a bug, I would knew exactly which SVN revision I would have to checkout in order to properly debug the system.


问:
Programming to an Interface and Keep Testability in Unique Classes
I try to program to an interface whenever possible, but when I have a class that fulfills a very specific and unique purpose, one that can't be abstracted. Is it correct for me to say that I've reached the limits of "abstraction" and that I need to just pass in the concrete class?

```<code>public void DoSomethingWith (HighlySpecificClass specificClass, ISomeInterface abstractedClass)
</code>```

So if the "program to an interface" is more a guideline than a hard rule, how can I make it testable? Should I create a "header" interface for it anyway?

答:
'Program to an interface' is a general, language-independent statement. With languages like C# and Java that have an explicit language feature called interface, this can lead to confusion.

The thing to remember is that both languages have at least two ways of defining interfaces;

explicitly, with a keyword

implcitly, by taking a class and making only the relevant bits accessible (with public etc.).

Knowing when to use which way of defining an interface is in general a judgement call.

Sometimes a specific technology or tool will make the decision for you. For example, if you were using a mocking tool that only supports mocking interfaces, and a particular test needs a thing to be mocked, then you are going to have to use an explicit interface.

But ideally you would use a less limited tool that supported both explicit and implicit interfaces.


问:
what is the difference between overengineering, underengineering and rightengineering?
What is the difference between over-engineering, under-engineering and right-engineering at coding/design perspective?

I found over-engineering: Coding too much like doing future requirement code and implementing simple logic as very complex code. Am I right?

and I do not understand under-engineering and right-engineering.

This terminology helps us to understand a design how is implemented in single word.

terms I found in this link

答:
"over engineering" means improving a solution when the cost of improving it is higher than the benefits of improving it. And "under engineering" means not improving a solution, when the benefits of improving it would outweigh the cost. Now guess what "right engineering" means...

Since a "simple" solution was mentioned, and was somehow correlated to inexperienced developers, sorry, but inexperienced developers often cannot find a simple solution. Experienced developers do find a simple solution if there is one, and it is often the "right engineered" solution, because it requires the minimal amount of work to get a working solution, it is often readable and maintainable because it is simple, it often (not always) is efficient because it doesn't waste time time on unneeded complexity.

Adding complexity isn't over-engineering either. Over-engineering, by definition, actually improves the product (just not enough to justify the cost of the improvement). The example given just added pointless complexity at no benefit at all.

And code isn't right-engineered when it's perfect. It's right-engineered when it reaches the point where the cost of improving it outweighs the benefits of improvement. If we can't even agree whether a change is an improvement or not, then it is very unlikely whether the change has benefits that justify the work of changing it.


问:
Storing session key in a hidden field
Background:

I have a question which is outline at Use different local storage between windows. The very high level question is "How can I keep tabs and windows sessions from clashing".

Requirement:

I want to be able to have separate "sessions" for each tab(s) or window(s).

Problem:

The problem is if I store the data in cookies or in HTML Local Storage, it will be very difficult prevent the user from screwing up the data by opening s new window or tab and keeping the data separate.

Possible Solution:

Since Tabs and Windows share cookies and HTML Local Storage under the same instance. My question to here is, how safe is it to store a unique key in a hidden field to use to retrieve the cookies or HTML Local Storage? By doing it this way, if a new page is created (or Tab), this field is not shared across tabs and windows. What's the security risk in this approach and its a good idea?

For example, I would store the session id or Key in a hidden field:

```<code>  <input type="hidden" name="sessionId" id="sessionId" value="" />
</code>```

答:
I thought about this a little bit to see how complicated it would be to have our web server support multiple sessions across multiple tabs. Disclaimer I just had a quick brainstorm about this and I have not done this in practice or even tried to implement something like this.  In order to take advantage of everything that cookies do and to not have a major rewrite on our client and server I wanted to keep using cookies for session management.

To do this we would make unique url paths and have that cookie be unique to that path, our application is single page so it would be pretty trivial to add an ending /GUID/ and just ignore it on the client and server.  Things might get complicated for multi page applications.

Previous way:

User goes to mydomain/app/ in two tabs and their session id cookie is shared across tabs.

Proposed way:

User goes to mydomain/app/ they are redirected to mydomain/app/{GUID}/ with a cookie path of mydomain/app/{GUID}/ a new tab is opened and they are redirected to mydomain/app/{NEXTGUID}/ with the {NEXTGUID cookie path.  When tab 1 communicates with the backend that tabs specific cookie is only visible to the server and the same thing with tab2.  The client knows nothing about its session id and the server just uses the session id that it is given, single or multiple tabs everything just works the same way.

Response to comment

No storing the session in the url is a bad idea for security reasons.  The guid would just make the cookies path unique to that tab, the session key is still in each cookie.  The guid and session id know nothing about each other.  The cookies could and should be httponly and not available to the client.

I think the benefit to this approach is that the client has no knowledge about how to manage sessions (the browser will send the right cookie and the associated session for that tab) and the server will just use the session from the passed in request.  The only thing that needs to get implemented on the server is adding something to the uri to make it unique per tab and have the session cookie use that uri when setting the path on the session cookie.  This will also allow for non browser based clients that don't care about tabs to have a clean api as well, they just need to send the session cookie in the cookie header.

Title: Storing session key in a hidden field


答:
If all you ever want to do is <compiler> **/*.<extension>, build scripts serve little purpose (though one can argue that if you see a Makefile in the project you know you can build it with make). The thing is - non-trivial projects usually require more than that - at the very least, you'll usually need to add libraries and (as the project matures) configure build parameters.

IDEs are usually at least that configurable - but now the build process relies on IDE-specific options. If you are using Eclipse, Alice prefers NetBeans, and Bob wants to use IntelliJ IDEA, you can't share the configuration, and when one of you pushes a change to the source control, they need to either manually edit the IDE-created configuration files of the other developers, or notify the other developers so they'll do it themselves (which means there will be commits where the IDE configuration is wrong for some of the IDEs...).

You also need to figure out how to do that change in each and every one of the IDEs used by the team, and if one of them doesn't support that particular setting...

Now, this problem is culture-dependent - your developers might find it acceptable to not have the choice of IDEs. But developers that have experience with an IDE are usually both happier and more efficient when using it, and text-editor users tend to get religiously zealot about their favorite tools, so this is one of the places where you want to give freedom to the developers - and build systems allow you to do just that. Some people might have a build system preference, but it's not nearly as fanatic as IDE/editor preferences...

Even if you get all the developers to use the same IDE - good luck convincing the build server to use it...

Now, that's for the simple build process customizations, that IDEs tend to provide nice GUI for. If you want more complex stuff - like pre-processing/auto-generating source files before the compilation - you'll usually have to write a pre-build script in some basic text area inside the IDE's configuration. Which build systems you would still have to code that part, but you can do it in the actual editor you write the code in, and more importantly: the build system's framework itself usually provide some support for organizing these scripts.

Finally - build systems are good for more than just building the project - you can program them to do other tasks that everyone in the team might need performed. In Ruby on Rails, for example, there are build system tasks for running database migrations, for cleaning the temporary files, etc. Putting these tasks in the build system ensures that everyone on the team can do them consistently.


问:
How to store passwords which need to be re-read
I have a utility which runs at certain intervals. My customer now wishes for it to send an email when the task is completed.

They want to be able to control the email address, meaning, they want to be able to enter their SMTP details.

This is quite a trivial task, but, the storage of the password is not.

When customers log onto a website, I hash it, using a salt but that's simply because I don't need to use the password, however, for email, I will need to send the email, probably in plain text.

I accept that sending the password over the network to the SMTP server in plain text is a risk, but that is not the question.

I'm more concerned about some one finding the password details in plain text within a text file or a field of a database. I need to offer at least some layer of defense.

It is just as simple as encrypting the password as such I can decrypt it?

答:
Assuming you own SMTP servers,

I would set up firewalled local instances of Node.js or something like that on the same machines where SMTP is located and store passwords encrypted on those machines. Setup proper local access permissions on those servers.

Then expose those instances for certain requests to certain IPs just to cover your main service.

In this case, your passwords are protected somewhat more because they are not accessible from outside. You don't need to store them in your main database.

UPDATE: With this architecture you are abstracting the communication to SMTP servers to Node.js instances. So you main application can really connect to anything going forward if you maintain the contracts.


答:
Consider using built-in password vaults.  For example, Windows 8 has a credential manager, Windows 7 has the Data Protection API, Apple has keychain, etc.

Note that such features primarily protect against password theft by a user without different credentials than the owner (e.g., on multi-user systems).

As you haven't explained your threat model, I'm unsure if this is sufficient.

Title: How to store passwords which need to be re-read

Body:
I have a utility which runs at certain intervals. My customer now wishes for it to send an email when the task is completed.

They want to be able to control the email address, meaning, they want to be able to enter their SMTP details.

This is quite a trivial task, but, the storage of the password is not.

When customers log onto a website, I hash it, using a salt but that's simply because I don't need to use the password, however, for email, I will need to send the email, probably in plain text.

I accept that sending the password over the network to the SMTP server in plain text is a risk, but that is not the question.

I'm more concerned about some one finding the password details in plain text within a text file or a field of a database. I need to offer at least some layer of defense.

It is just as simple as encrypting the password as such I can decrypt it?


问:
What is the best way to remember a successful execution over several program calls?
I'm working on a build process, that is called manually over the command line.

To check if it exited unsuccessfully during the build I want to set a lock file (symbolic link) and remove it on successful exit.

But: I don't want to rely on the existence of build files and the absence of a lock file to signal a successful build.

Is it a good practice to just set another 'lock' if the build process was successful, that I can check for existence? If so, is there a better term for it than 'success lock'?

Note: I'm building .iso files and they are created, whether the build process exits successfully or not.

Furthermore, I'm only a beginner and do not use, nor am I familiar with any industry tested frameworks or procedures. I only want to check if the files I want to "put into" the .iso file were aggregated completely. So that would be the only bit of information I require.

As the build runs locally on my machine I'm not concerned about race conditions and the like. It is merely to see, if, when repeating a build, I can immediately start putting the .iso together, or if I have to start the aggregation part over, because it didn't finish successfully.

I'm using Xubuntu Linux 14.04, but since I'm really only looking for a best practice, it shouldn't matter, I think.

答:
One possible solution:

Upon execution, create a temporary file and store the status in it. Useful to keep logs as well.

Delete the file every time new execution starts and you no longer need it.


问:
arbitrary data shared between plugins
I'm making a program that supports plugins.  The program is being written in F#.

The program maintains a single object that represents the state of the program.  When a plugin is invoked, it takes the state and returns a new state which replaces the old one.

Example:
The filereader plugin takes an empty state and puts the contents of a specified file into the state.
The textviewer plugin takes this state, checks if it contains a "text" object; if it does, it displays the text on the screen.

In this way, a filereader can be implemented seperately from the textviewer.  The textviewer only cares if there is a "text" object in the state; it does not care how the object got there.

My question is of implementation.  I could represent the state as a big JSON object.  But this is rather clumsy (but it isn't too bad).  I could also use System.Object to hold arbitrary data, but is this a good approach?

答:
First, you probably want to use Event Driven architecture in this case, or something similar to decouple all the modules. Once module is done doing what it's doing, it triggers an event on the main program that all other modules are subscribed to.

Now, to your question:
I would only store the references to resources provided by the modules in the state - not the whole text file as you described.

Text Reader Module is attached to main program.

Module is updating the state with new reference to the text file that it stores somewhere.

Text loaded event is dispatched.

Text Viewer is subscribed to the event, and thus pulls the file by reference from the state.

Your state object should represent a collection of assets probably utilizing Decorator pattern and potentially Composite pattern to treat collections of collections as just assets if required.

That's roughly what I would do. Of course, this would change a bit as you design and implement as I am making a lot of assumptions here.

Title: arbitrary data shared between plugins


问:
Is it ok to include jQuery in a jQuery plugin?
The question jQuery plugin file including the jQuery library came up today on stackoverflow, and I strongly advised against including jQuery in the plugin.

I didn't really get any support from others on this; in fact there was more support to include jQuery than not. Is this ok or are there good reasons not to do this? I think it's a really bad idea as I think it should be up to the developer using the plug as to what version of jQuery is being used.

答:
Absolutely not! It's like including a vehicle when someone purchases a set of tires.

Plugin is addition to something, not a copy of it with addition.


答:
Plugin architectures is quite a well-known problem in Object-Oriented Design, where it's usually addressed by defining a set of interfaces that the host program expects the plugins to implement.

On .NET, the Managed Extensibility Framework was explicitly designed to address this problem. Not only does it support interfaces that are defined in advance by the host program, but it can also discover and compose interfaces that one plugin requires (imports), and another plugin implements (exports).

Other mature DI Containers that support convention-based Auto-registration can be configured to supply the same features.

In F#, substitutability and composition is usually achieved with functions instead of interfaces, but I'm not aware of any DI Containers or other composition engines that work on F# functions instead of .NET interfaces. Since I mostly favour Pure DI these days, I also hope never to see this happen.

You may wonder why this is relevant in an F# context, but once you realise that there's a strong relationship between objects and closures, the relevancy may become more apparent.

In any case, the architecture suggested here isn't how plugin architectures are normally implemented. As explained above, plugin architectures are usually defined around a set of predefined behaviours, rather than data. Well-designed interfaces define behaviours, just as functions do. These are strongly typed and substitutable (polymorphic).

Weakly typed data is likely to become a maintenance headache over time, so I wouldn't go with that design.

You can read more about (Object-Oriented) loosely coupled architectures in my book.

You don't write about your root cause for writing an application with a plug-in architecture, but unless you're writing a big shrink-wrapped application like Visual Studio, a browser, a general-purpose web server, or the like, this sort of architecture is most likely overkill.

One of the best features of F# is that it prohibits cycles. In Object-Oriented languages like C# and Java, people often utilise component-based architectures like Ports and Adapters, Onion architecture, layers, etc because at the module level, cycles are prevented (you can't easily create cycles with hard dependencies). However, in F#, you get this assistance from the language itself, so there's much less reason to address coupling with architecture; coupling is already addressed by the language.

Title: arbitrary data shared between plugins

Body:
I'm making a program that supports plugins.  The program is being written in F#.

The program maintains a single object that represents the state of the program.  When a plugin is invoked, it takes the state and returns a new state which replaces the old one.

Example:
The filereader plugin takes an empty state and puts the contents of a specified file into the state.
The textviewer plugin takes this state, checks if it contains a "text" object; if it does, it displays the text on the screen.

In this way, a filereader can be implemented seperately from the textviewer.  The textviewer only cares if there is a "text" object in the state; it does not care how the object got there.

My question is of implementation.  I could represent the state as a big JSON object.  But this is rather clumsy (but it isn't too bad).  I could also use System.Object to hold arbitrary data, but is this a good approach?


问:
How to define dependent function in node js?
I have a nodejs project in which a sample.js include two function
function A depends on function B's callback .

```<code>// smaple.js
        Both function are included in the same file
        function B ( arg1 , callback ){
            // do some async
            async.map(arg1 , function(item, cb){
                     var a = item.a
                     var b = a*4
                     cb( null , {'a':a,'b':b})
                },function(err , result){
                callback(err , result)
            } )

        }

        function A ( arg , callback ){
            if(condition1){
            callback(null , 1)
            }else{
             B ( arg , function( err , result){
                if(err){
                 callback(err , result)
                }
                else if (result ==1 ){

                callback ( null , 2)
                }else{
                callback ( null , 1)
                }

             })
            }
        }
</code>```

Scenario 2

```<code>        // function B is in outer.js and included as module
        sample.js

        var outerfunction = require('./outer.js');

        function A ( arg , callback ){
            if(condition1){
            callback(null , 1)
            }else{
             outerfunction.B ( arg , function( err , result){
                if(err){
                 callback(err , result)
                }
                else if (result ==1 ){

                callback ( null , 2)
                }else{
                callback ( null , 1)
                }

             })
            }
        }

        outer.js

        function B ( arg1 , callback ){
            // do some async
            async.map(arg1 , function(item, cb){
                     var a = item.a
                     var b = a*4
                     cb( null , {'a':a,'b':b})
                },function(err , result){
                callback(err , result)
            } )

        }

        module.exports.B = B ;
</code>```

Does scenario 1 is a proper way to use function ?
What will happen if this code run concurrently using cluster module?

Does scenario 2 is better way to use dependent function ?
Is this code perform better on concurrent execution?

答:
Both cases will do. You just have to maintain the chain of methods to execute.

If you have one method dependent on another method, one of the way's of maintaining the chain is to call the second method inside the callback to the firs one just like you are doing I believe:

Example:

```<code>function bar(param) {
    console.log(param);
}

function foo(param, done) {
    if(param === 1) {
        return done(param);
    }
}

foo(1, bar);
</code>```

Body:
Both cases will do. You just have to maintain the chain of methods to execute.

If you have one method dependent on another method, one of the way's of maintaining the chain is to call the second method inside the callback to the firs one just like you are doing I believe:

Example:

function bar(param) {
    console.log(param);
}

function foo(param, done) {
    if(param === 1) {
        return done(param);
    }
}

foo(1, bar);


答:
I don't see these necessarily as opposites.

I think of over-engineering as providing options or provisions for capabilities that are not yet or not yet know to be necessary.  For example, and method parameter that only has one value that is ever used; an abstract class that has only one subclass.  These things add complexity to maintenance and cost time to develop, and may be never used.  Even if some similar option is needed in the future, it can turn out that the implementation wasn't right and needs to change anyway.  Best to refactor and introduce optionality when there are at least two options known to be used.

I think of under-engineering as not doing enough to handle the design; not in terms of options but in terms of quality.  For example, not handling error conditions, or having race conditions. The code may run when the stars align, and, the even if stars align mostly, when they don't the code just breaks; it doesn't work.

By way of not seeing them as opposites, I think you can find both under- and over-engineering in the same project, the same file, the same method, even.  Unused options, yet not robust, not stable.

Title: what is the difference between overengineering, underengineering and rightengineering?

Body:
What is the difference between over-engineering, under-engineering and right-engineering at coding/design perspective?

I found over-engineering: Coding too much like doing future requirement code and implementing simple logic as very complex code. Am I right?

and I do not understand under-engineering and right-engineering.

This terminology helps us to understand a design how is implemented in single word.

terms I found in this link


问:
Do binary trees serve a specific purpose in storing hierarchical data? What is their canonical use?
I understand the structure of binary trees and how to traverse them. However, I am struggling to realize their actual uses, purposes in programs and programming. When I think about 'real life' examples of hierarchical data they almost certainly have more than 2 children. For example, in a family tree, a mother may often have more than two children.

Are 'binary trees' really only useful to store linearly related data due to the faster processing times over arrays and lists? Alternatively, do they serve a specific purpose in storing hierarchical data? If so, what examples are there of the application of binary trees. What data is such that a node has at most 2 children?

答:
No, binary trees are not for storing hierarchical data in the sense you're thinking of.  The primary use case for n-ary trees, where n is a fixed number, is fast search capability, not a semantic hierarchy.

Remember the old game where one person thinks of a number between 1 and 100, and the other has to guess it in as few guesses as possible, and if you guess wrong the person thinking of the number has to tell you if you're too high or too low?  It gets boring after a while because you quickly figure out that you should always start at 50, then go to 25 or 75, and keep dividing the range to be searched in half with each new guess after that, and eventually you can guess any number in at most 7 guesses, guaranteed.

It may not make for a fun game, but that property is what makes binary (and other n-ary) trees useful: you can use them to search a very large data set in a very small amount of time.


答:
We should not forget that the whole is greater than
the sum of its parts. I could imagine a situation where a user exists and his phone number is unknown.. Is the user an instance of ICallable?
To be 'callable' and to be 'a user' are two different things. So, design of your interfaces should reflect this notion.

I think that your question is not about technical aspects, but rather about your domain area.

Title: Programming to an Interface and Interface Segregation in the Context of a User Class

Body:
I try to program to an interface whenever possible, but its not clear to me how I could apply it to a model as broad as a user. Which can hold many disparate fields (name, age, phone number, ssn, etc.) or be composed of many modules.

I could design a general purpose library of functionality for use across applications, that would take in an ICallable to make a phone call or INameable to display a name to the console. But in the end the user class (how the data is accessed and/or stored) would be unique to an application and its needs.

If I try to design the user and consumers in the library (stated above) to communicate by interface, I get an "interface soup" (or something "hydra-esque") on the user class. Where it feels like I'm extending an interface for almost every attribute or module.

```<code>public class Employee : INameable, ICallable, IAgeable, IPayable ...
</code>```

Is this particularly wrong? Am I taking interface use too far by completely avoiding the injection of concrete classes into the consumer (and preventing more general use)?

Whats a better approach to this problem?


问:
Combining simple and complex APIs in a web application?
We use C# MVC and Angularjs as the primary tools to develop our web applications.  We've recently been discussing best practices, with an eye towards revising our development approaches into something a bit more structured.

One of the topics is how we handle APIs.

More specifically, we're looking to utilize web APIs as a means of communicating from the client-side AngularJS controllers and the server-side C# controllers.  Basic model data would be passed from the C# controller through the view into the DOM, but dynamic elements would be loaded via Ajax calls to the web APIs.

This led to the question: how do we organize our APIs?

Our data models for these APIs seem to generally fall into one of two categories: complex models representing data object hierarchies, and simple models for dynamically populating the view (such as loading ng-options for select tags).

We're not planning on going fully RESTful, unless the specific project identifies that APIs will be exposed to third party entities, since properly configuring HATEOAS seems overkill for APIs that are intended as purely internal.

An alternative to having both complex data object APIs and very simple APIs would be to only use complex data objects, and to include in those objects every dependent list that could be needed within the view.  My main concern with that approach is that some of these complex models could get very large, which could significantly impact performance.  Of course, a ton of small API calls could also impact performance.

By way of example, one of the objects in a current project is a document type that can have one or more tasks associated with it (and each task is associated with a single parent document).

Within the module associated with that document, loading all of the tasks associated with it as part of the main API call makes sense.  However, that document object is referenced in other places within the application where we want the users to choose one instance of that document type, at which point a second drop-down becomes populated with all the tasks associated with that document.

Having a page load hundreds or thousands of these documents, including up to half-a-dozen or so tasks for each of those documents, seems likely to be a bigger hit to performance than a single call to retrieve the ID and description of each document, and then having a second API trigger on selection, which would load the task drop-down with just the tasks associated with that document.

Is this strategy of mixing complex model APIs and simple APIs a good idea?  What are the main pitfalls to watch out for?  Is there a better architecture to employ?

答:
One approach I like, to use your own term, is having "complex models" but asking the server how deeply you want the model to be filled.

In your example, you might have an API call:

```<code>GET /project?id=1337
</code>```

That will return some basic representation of your model with attributes common across all use cases. Now you might be able to call the API with additional parameters:

```<code>GET /project?id=1337&include=tasks
</code>```

You can use these parameters to indicate that the server should include additional data in your model. You could support multiple mutually exclusive includes, conventions based on "paths" in your model, or whatever you want.

I like this because you only need a single API but it can support multiple use cases. And it works well with caching and other optimization strategies.

Body:
One approach I like, to use your own term, is having "complex models" but asking the server how deeply you want the model to be filled.

In your example, you might have an API call:

GET /project?id=1337

That will return some basic representation of your model with attributes common across all use cases. Now you might be able to call the API with additional parameters:

GET /project?id=1337&include=tasks

You can use these parameters to indicate that the server should include additional data in your model. You could support multiple mutually exclusive includes, conventions based on "paths" in your model, or whatever you want.

I like this because you only need a single API but it can support multiple use cases. And it works well with caching and other optimization strategies.


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答:
Hmm, the current answers center too much on technical aspects, and the readability pros/cons (which is an important point). So let me try to shift it a bit more onto the PHP environment/community:

PHP is Perls little stepsister. And an integral part of Perl are regular expressions (they invented that stuff, didn't they?). Therefore it's one cause why regexps are pervasive in PHP too.

The use case of PHP is coincidentally not much unlike the use case for regular expressions. PHP is structurally used for glueing together HTML pages. And regexps work on text. (what WReach said)

Micro optimization. As mentioned before: people use regexps and/or PHP string functions frequently after perceived speed. A core problem in PHP circles, not specific to regexps.

Regular expressions are built-in. In Python, in Java, in C#, in Ruby? there is availability, but a deterrent in having to load an extra module. And see how in PHP or Javascript where it's a core feature, the usage pattern differs. Another exhibit: CSS where it's getting more frequently used.

The PHP manual is at fault. It often is. Regular expressions are easily discoverable, and I postponed this fun fact because it's boring in its obviousness: all the damn tutorials and PHP introduction books always teach about regular expressions, but fail to educate on use cases.

The string API in PHP was designed by the same people that brought you magic quotes and the namespace \ separator. It's encompassing, better than Java, but not glamorous in its entirety. Particularily if strings could double as objects (see Python), string functions might outdo regexps.

But that just as side notes. I believe it's anyway mostly perceptional and technical reasons that lead to overuse and/or shunning regular expressions in general. Yet PHP and its userbase has a few properties which compound it, and why we see more questions on SO about it [citation needed!] and they are "morbidly attractive" there.


问:
Testable design in Swift
I've been searching for so long about how to design testable classes in Swift but every information site just describe basic stuff like how to test, how to assert, why is testing  good...

My current design (which I'm not so sure is the best) includes a singleton ApiClient class that gets initialized on the AppDelegate. Something like this:

```<code>// Inside AppDelegate#application:didFinishLaunchingWithOptions
ApiClientFactory.make();

// Inside ApiClientFactory
static func make() {
    ApiClient.initialize(
        userProvider: UserProvider(UserLocalRepo(), UserRemoteRepo()),
        booksProvider: BooksProvider(BookLocalRepo(), BookRemoteRepo()),
        ...
    )
}
</code>```

The idea was to inject into the *Providers classes, mock repos when testing. But due to the way VCs are instantiated I'm not sure this is a good design at all, and I'm not sure where would I inject those mock repo, as it seems AppDelegate#application:didFinishLaunchingWithOptions still runs on tests (which means ApiClient will be initialized with the actual classes, not the mock ones)

答:
I think you're running into a common pain point while testing and one of the reasons I dislike singleton implementations. Injecting these repository instances is a useful pattern allowing you to substitute test doubles or change the configuration of the API client in the future without needing to modify its implementation. However by implementing it as a singleton you lose much of this flexibility, as you seem to have noticed. Not only will you have to deal with your application:didFinishLaunchingWithOptions: method being called but you also need to be careful not to allow shared state in this singleton to leak from one test into subsequent tests.

One option would be to allow those repositories to be modified after initialization so you can later replace them with test doubles. Unfortunately that also allows for a mutable configuration which you may not want to allow in your app.

My preference would be to not use a singleton at all and replace this ApiClient class with an instance of the class injected into whichever components need to use it. You can then create independent instances isolated to each test as necessary. In your application perhaps you will still only have a single ApiClient instance but that doesn't mean it needs to be accessed via class methods or enforced as a constraint of its implementation.

Title: Testable design in Swift


问:
REST API: Resource Ownership
Let's say there are Users and Pets. Each Pet has a single User as its owner, and a globally unique id. Endpoints could be

/users/1/pets/2

/pets/2

I feel like the first option could be unintuitive since IDs are inconsistent within one User. Which one should I use?

答: If a pet only exists in the context of a user, then it makes sense to make pet a subresource of user. But if you can envision the pet as a standalone resource as well, then it would be intuitive to put it on its own path. Ideally, you would structure your resources the way you think about them.</p>

Title: REST API: Resource Ownership


问:
How to determine if a class meets the single responsibility principle?
The Single Responsibility Principle is based on the high cohesion principle. The difference between the two is that a highly cohesive classes features a set of responsibilities that are strongly related, while classes adhering to SRP have just one responsibility. </p>

<p>But how do we determine whether a particular class features a set of responsibilities and is thus just highly cohesive, or whether it has only one responsibility and thus adheres to SRP? In other words, isn't it more or less subjective, since some may consider a class very granular (and as such will believe the class adheres to SRP), while others may consider it not granular enough? </p>

答:
Just for the sake of discussion, I will bring up a class from JUCE called AudioSampleBuffer.  Now this class exists to hold a snippet (or perhaps a rather long snippet) of audio. It knows the number of channels, the number of samples (per channel), seems to be committed to 32-bit IEEE float rather than having a variable numeric representation or wordsize (but that is not a problem with me).  There are member functions that allow you to get the numChannels or numSamples and pointers to any particular channel.  You can make an AudioSampleBuffer longer or shorter.  I presume the former zero-pads the buffer while the latter truncates.

There are a few private members of this class that are used for allocating space in the special heap that JUCE uses.

But this is what AudioSampleBuffer is missing (and I have had several discussions with Jules about it): a member called SampleRate.  How could it be missing that?

The single responsibility that an AudioSampleBuffer needs to fulfill is to adequately represent the physical audio that one hears that its samples represent.  When you input an AudioSampleBuffer from something that reads a soundfile or from a stream, there is an additional parameter that you must get and pass it along with the AudioSampleBuffer to processing methods (say it's a filter) that needs to know the sample rate or, eventually, to a method that plays the buffer out to be heard (or streams it to someplace else).  Whatever.

But what you have to do is continue to pass this SampleRate, which is inherent to the specific audio living in the AudioSampleBuffer, around to everywhere.  I have seen code where a constant 44100.0f was passed to a function, because the programmer didn't seem to know what else to do.

This is an example of failing to meet its single responsibility.


问:
Is there an established software taxonomy that's based on the type of software?
I'm researching engineering approaches to software development based on the type of software, for example:

Custom one-off software (e.g. space shuttle software)

Whitebox application requiring customised (e.g. Apache Ofbiz ERP - source code is usually downloaded and customized for each implementation)

Blackbox application without extension points

Blackbox application with extension points for customisation (e.g. MS Word, SAP)

...

Is there an established taxonomy of different types of software based on how the software is implemented?

答:
Most software taxonomies tend to focus on the end user rather than developer interested in implementation aspects.

I compiled a list of those I am aware of in descending order based on how developer v. end-user oriented is the taxonomy.

Free software taxonomies

Software taxonomy on Unilexicon, based on PyPI - collaborative editing welcome

Python package index (PyPI) taxonomy

Software branch of the DMOZ taxonomy

Google Products Taxonomy has a software branch

Paid taxonomies

A taxonomy of software types to facilitate search and evidence-based software engineering

WAND Information Technology Taxonomy


问:
How should I handle test services not connecting to Production DB?
I want to verify that my services (used to collect data from database and handle it according logic) are not connecting to production database which can cause data loss.
my first idea was to mark the service with its configuration file with Enviroment property and verify it against DB's data but our QA enviroment database is replicating its data from production DB so I can't rely on Database data.</p>

答:
A number of options:

Using firewall, block anything from accessing production database except a few servers that are allowed. This should be done always in production.

Define production configuration on the production server and don't check it in source control. Source control should maintain only development configuration file with the development connection strings.

Use different roles in the database for different environments. Say service-dev and service-prod. With service-dev not having access to production.


答:
This is going to depend on what language you're using, but you should have one configuration for debug and one for production.

You can either focus on ensuring the wrong config is never deployed with your project, you can never run the project on the same server as the database is on (assuming you have disabled remote DB connections), or you can make sure that the wrong config cannot connect to your production site.

I would suggest simply having a different password on your production site to the debug site, so if the test application accidentally tries to connect to the production server, it will get an access denied error.

You can usually do this by having a different role. For our setup, we use windows authentication on debug/test servers, but live requires a specific database user with a password, and windows authentication doesn't work. This means there is no possible way anything other than production code can hit the production server/database.

Title: How should I handle test services not connecting to Production DB?

Body:
I want to verify that my services (used to collect data from database and handle it according logic) are not connecting to production database which can cause data loss.
my first idea was to mark the service with its configuration file with Enviroment property and verify it against DB's data but our QA enviroment database is replicating its data from production DB so I can't rely on Database data.</p>


问:
interpretation of the statement in java
I am confused over the interpretation of the following statement

```<code>Fruit x= new Fruit();
</code>```

My interpretation is that the new operator along with Fruit(); creates a new object somewhere in the memory.

Now x is a reference variable that points toward the object created and if I write Fruit x , does it only mean that a reference variable is created which points no where?

Can i also say that x keeps the memory location of the object?

答:
You are absolutely correct.

new operator reserves space in memory for a new object of Type Fruit. Assignment = assigns the reference to your variable x.

If you were to write Fruit y = x;, you would only create a new reference, so both y and x would still be pointing to single location on memory.

For more in-depth knowledge, check out this article.

Title: interpretation of the statement in java


问:
Using open source apps source code under Apache v2
I modified some code and added few (minor) changes to an open source Android app. Now I want to publish it on play store. The app is licensed under Apache license v2. The license file is included in the project but there is no name of the author on it. It is just an Apache terms and conditions file nothing else.

There is no copyright note anywhere in the project. What should I do? Should I publish it without the license? I can get the name of the author by visiting his profile (the project is on GitHub). Should I add a copyright notice in code?

答:
You need to read and understand the entire license.

Here are a few noteworthy points:

Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual... ...no-charge,...  ...copyright license to reproduce, prepare Derivative Works... ...and distribute the... ...Derivative Works in Source or Object form.

Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

You must [include...] a copy of this License; and

You must cause any modified files to carry prominent notices stating that You changed the files

So the quick answer is that you may redistribute the software, with or without modification, provided that you continue to do so under the same license, following its terms. This is a common condition of many open source licences. But again, you must read the license itself for its actual terms and conditions.

For a legal opinion of a particular situation, or possible legal ramifications, you should consult a lawyer knowledgeable in intellectual property law.


答:
You have stated your choice that pets have a globally unique id.  This means that a pet can be transferred to another owner without changing the pet's id (generally a good thing for stability under db refactoring). Further, it means that should you want to, you can have two owners (e.g. a couple or roommates, etc..) for the pet.  (Not to mention directly referencing a pet as you note.)

Therefore, I'd say use the /pets/<id>.

However, you can still list pets for one user with /users/1/pets, and user for pet with /pets/<id>/user (if limited to one or /pets/<id>/users for more), for one, because we're talking about the API here not your normalized database hidden behind it.  The use of simple integers for ID's may be confusing (so you could use something else), but when people see that /pets is an endpoint, I think they'll get it.

Have a look a OData, if you haven't seen it already.  A good way to layer on top of REST, and provide for filters, nested data, even doing joins, from an API perspective. For example, https://stackoverflow.com/q/3920758/471129 gives a good discussion about using navigational properties for specific joins without having to introduce foreign keys.

Also, I think you will eventually want to remove the limitation of one owner per pet, as this is not going to stand the test of time.  Cars, houses, bank accounts, all have notions of multiple owners.  Children can have multiple guardians, why not pets having multiple owners.

Title: REST API: Resource Ownership

Body:
Let's say there are Users and Pets. Each Pet has a single User as its owner, and a globally unique id. Endpoints could be

/users/1/pets/2

/pets/2

I feel like the first option could be unintuitive since IDs are inconsistent within one User. Which one should I use?


问:
What does "Automatic Receipt" in license mean?
I see the following statements in Arphic Public License:

Automatic Receipt

Each time you redistribute the Font, the recipient automatically
  receives a license from the original licensor to copy, distribute or
  modify the Font subject to these terms and conditions. You may not
  impose any further restrictions on the recipients' exercise of the
  rights granted herein. You are not responsible for enforcing
  compliance by third parties to this License.

English is not my native language. I don't want to mis-interpret it. My understanding is that it describes how the APL license propagates between users. It doesn't imply any extra physical documents besides the APL license itself.

答: Correct.  It is clarifying that you can't prevent users who you distribute this font to from receiving this same license you received.  You can't by licensing restrict or impede their usage of the font.  Using the term "automatic receipt" is just indicating this happens automatically not that there is any additional physical documentation.  You don't have to generate or provide the user any additional "receipt" that they have received the license.</p>


问:
What are the advantages of build scripts?
For most of my programming career, I've used the "build/compile/run" command in whatever IDE I'm working with to produce a runnable program. This is one button, pretty easy. As I learn more about different languages and frameworks, though, I see more and more talk of "build scripts" (ANT, Maven, Gradle, etc.) to get a project running. My understanding of these is that they are instructions to the compiler/linker/magical-program-maker that specify configuration details - minutiae.

I remember writing makefiles back in school, but I didn't see any special advantage then (we only used them when writing in a Unix terminal, where an IDE with it's handy "build" button wasn't present). Beyond that, I've seen other questions on here that discuss how build scripts can do more than just create your program - they can run unit tests as well as secure resources regardless of the host machine.

I can't shake the feeling that build scripts are important to understand as a developer, but I'd like a meaningful explanation; why should I use/write build scripts?

Responsibilities of Build Script and Build Server discusses the role it plays within a broader scope. I'm looking for specific advantages offered by a build script versus an IDE's "build/run" command or similarly simple methods.

答:
The above answers cover a lot of good ground, but one real-world example that I'd like to add (that I can't add as a comment due to no karma), is from Android programming.

I'm a professional Android/iOS/Windows Phone developer, and I use Google services APIs (mostly Google Maps) a lot.

In Android, these services require that I add a keystore, or a type of developer ID file that tells Google that I am who I say I am, to a developer console. If my app is compiled with a different keystore, the Google Maps section of the app will not work.

Instead of adding and managing a dozen keystores to the developer console, only one of which can actually be used to update the app anyway, I include this keystore in our secure repo and use Gradle to tell Android Studio exactly what keystore to use when building for "debug" or "release". Now, I only have to add two keystores to my Google developer console, one for "debug" and one for "release", and all of my team members can clone the repo and get right to developing without having to go in to the dev console and add the SHA hash of their particular keystore, or worse, making me manage them. This has the added benefit of giving each team member a copy of the signing keystore, meaning that if I am out of the office and an update is scheduled, a team member only needs to follow a very short list of instructions in order to push an update.

Build automation like this keeps builds consistant, and reduces technical debt by cutting way down on set-up time when we get a new developer, a new machine, or when we have to re-image a machine.


问:
Using a GNU GPL licensed component in a BSD licensed software
I am currently in process of writing a software application.
In this application, I use another software project which is licensed by GNU GPL. I have widely modified the GNU licensed component and tailored it to fit my needs.

But I do not want my software application to be released under GNU GPL license, I would rather want it to be licensed by BSD.
My question is that how is it possible?

The GNU website says something about an "arms length" but it is still very unclear to be that what they mean by the arms length.
Is it possible if I use the modified component as a JAR in the main project?

答:
If you absolutely must use the GPL code but want to keep your project BSD licensed, you can:

rewrite the GPL code base or use a different option if available

write binary wrappers around GPL code (something simple like stdin/stdout works)

By using a wrapper that operates on streams (or any form of inter process communication), you have the ability to configure any program that can perform the same task and you don't need any interface files from the original code.  This would let you start off with a BSD licensed wrapper around the GPL code (creating a GPL derivative binary), but later shift to a more permissive code base if you have the time to write a replacement or happen to find a more permissive replacement (softwarerecs.stackexchange.com) and eventually include the permissive code replacement directly to avoid the overhead of the wrapper.