答:
Your question is quite hard to follow, and I'm unsure which issue you want answered. My contribution is to point out that

at the assembly language level, there is absolutely no difference between a pointer and a value, and both can be stored in memory or loaded into a register

at the level of a C-like language a distinction is made between pointers and values so that the compiler can help you use them correctly

at the level of a higher level language there are no pointers, just values and references.

The main purpose of a higher level language and the compiler that supports it is to free you from thinking about machine level details. Pointers are such a detail, not part of the solution for any computing problem but merely part of the implementation detail of the program that executes the solution.


问:
Difference in orientation of Sobel mask gives different edge detector result
I am implementing a Canny Edge detector for a class which I have based off the code found here. For the first derivative mask that I will convolve with the image, I am using the Sobel mask, although the website uses the Prewitt. As you can see in the samples on the website, the code is perfectly functional. However, I noticed different results when I changed the "orientation" of the Sobel gradient mask as I explain below.

The typical mask for taking the derivative in the x direction in my class notes is shown to be:

```<code>[-1 0 1]
[-2 0 2]
[-1 0 1]
</code>```

For the y direction it is:

```<code>[-1 -2 -1]
[0 0 0]
[1 2 1]
</code>```

For an experiment, I changed the orientation for the x direction to:

```<code>[1 0 -1]
[2 0 -2]
[1 0 -1]
</code>```

And for the y direction:

```<code>[1 2 1]
[0 0 0]
[-1 -2 -1]
</code>```

Oddly enough, this gives me two different results, which I did not expect, since I don't think the "direction" that I am using for taking the gradient should give me a different result.

First result:

Second result:

Why am I getting this different result? Where should I investigate next?

答:
Some questions, then a suggestion.

Have you tried your code with the same images and masks as the article. Do you get the same results?

Did you try switching masks in the original?

A quick scan of the source code tells me that this code is not easy to verify. It's not written in a way to ensure correctness, and it's not testable. I thought I found a problem in the iteration over Filter in Differentiate but on second thoughts it's probably OK.

What I did find is this in DetectCannyEdges:

```<code>if (((-157.5 < Tangent) && (Tangent <= -112.5)) || ((67.5 < Tangent) && (Tangent <= 22.5)))
</code>```

The second part of that looks wrong. It should be:

```<code>if (((-157.5 < Tangent) && (Tangent <= -112.5)) || ((22.5 < Tangent) && (Tangent <= 67.5)))
</code>```

Or I could be completely wrong.

ContentLicense: CC BY-SA 3.0

Body:
Some questions, then a suggestion.

Have you tried your code with the same images and masks as the article. Do you get the same results?

Did you try switching masks in the original?

A quick scan of the source code tells me that this code is not easy to verify. It's not written in a way to ensure correctness, and it's not testable. I thought I found a problem in the iteration over Filter in Differentiate but on second thoughts it's probably OK.

What I did find is this in DetectCannyEdges:

if (((-157.5 < Tangent) && (Tangent <= -112.5)) || ((67.5 < Tangent) && (Tangent <= 22.5)))

The second part of that looks wrong. It should be:

if (((-157.5 < Tangent) && (Tangent <= -112.5)) || ((22.5 < Tangent) && (Tangent <= 67.5)))

Or I could be completely wrong.


问:
Go-like interfaces + multi-methods make sense?
Thinking about the design of a potential new language, I wonder how related are the concepts of built a OO similar to GO interfaces and multi-methods (I get this from http://docs.julialang.org/en/latest/manual/methods/).

If I understand this right, the interfaces are simply a group of methods that must be implemented by each descendant, and multi-methods provide a nice way to specialize them without do a lot of boilerplate or casting.

However, Is my intuition that both could work well together, but wonder if is correct. For example, if a interface declare:

```<code>type Animal interface {
    Speak() string
}

func (d Dog) Speak() string {
    return "Woof!"
}
</code>```

but in julia is more like:

```<code>speak(x::Dog) = return "Woof!";
</code>```

So this feel like that both do the same, but different. Will be a mess to do both? When could that make sense?

Also, what make a "better" path, if only one must be used?

答:
Given that languages already exist that bracket the possible behaviours you are considering, the question is: which would suit your users better?

To create a programming language you need an intended audience of developers who will use it. When you ask a question of this type you then ask which choices will suit your intended users better.

If your users come from a specific community (say converts from C, C++, C#, Java, Go or Julia) then you choose to either provide something familiar, or something with specific benefits. Read the Go rationale to get an idea of how that works.

If your intended users are academics, or language freaks, or language dilettantes, then you strive to provide something novel and interesting, whether it is useful or not. A language like Befunge comes to mind.

If the only user is yourself, do what you like. Literally.

My audience has always been developers who want their lives made simpler by hiding unnecessary detail. The Julia approach looks pretty good to me. I can't tell you what the consequences will be until I know who your users are.

So if the target is developers that do business apps, web backends, mobile and you want to make their lives easier, then take an app written in some language and see how you would rewrite it in your new language in (say) half or a quarter or a tenth of the lines of code. What detail will you hide? Where will you hide it?

Scripting languages like python/perl/ruby are implemented in C/C++. They hide things like memory allocation, pointers, hashes and linked lists, string searching, loops by using garbage collection, references, associative arrays, regular expressions and map/apply logic. The code is still down there in the runtime, but the language operates at a higher level.

Maybe you can take concepts like these are move up to an even higher level with declarative code, goal-seeking and pattern matching, but that would be an entirely different question.


问:
Are (C) object files created with different compilers binary-compatible?
I understand that C++ compilers are not compatible with each other. However, I was unable to find anything on this topic for C in particular. I know that the C standard leaves a lot of room for compilers to implement things however they see fit: for example, the size and alignment of most (all?) data types is implementation-defined save for some minimal guarantees. Therefore, two compilers (or two versions of the same compiler) can disagree on numerous details.

Am I correct in thinking that there's no guarantee that two object files compiled with different compilers will actually link properly? For example, the size of pointers could be 32 bits in one object file and 64 bits in the other. But if that's so, why are C libraries sometimes distributed in precompiled form? Is there an expectation that I'll use the same compiler they did (e.g. gcc), or some de facto standard being used to ensure binary compatibility? And how do other languages with a Foreign Language Interface ensure things will line up properly when linking with C object files?

答:
The general answer is no, C language compilers are not compatible with each other. The C language standard does not define any kind of binary interoperability, and most compiler writers don't even try.

I need to qualify that. The objects emitted by a C compiler have to be linked with runtime libraries to produce either an executable or a runtime linkable library. Although the visible functions provided by the C runtime library should be compatible, there will also be non-visible functions that are unique to the implementation and prevent interoperability.

This lack of compatibility also extends to different versions of the same compiler. In general, programs and libraries compiled with older and newer versions of a compiler cannot be linked together, and those compiled with MSVC cannot be linked with those compiled by GCC.

There is a specific and very useful exception. Every platform provides a dynamic linking ABI (Application Binary Interface) and any program in any language that can conform to that ABI is compatible. Therefore it is generally possible to build a DLL (on Windows) with MSVC (or something else) and call it from a program compiled by a different version of MSVC or by GCC and vice versa.

There are two other ABIs on Windows: COM and .NET assemblies, and they span a wide range of languages. So interoperability is definitely possible, but compatible they are not.

The degree of incompatibility can easily be seen by comparing the linker maps. For GNU use ld -M, for MSVC use link /map. Study the two generated files. Both will have names in them that you recognise, such as printf and main, although (depending on options) the names are likely to be mangled in various ways. They will also have names that are completely different, many of which you won't recognise. In order for object files produced by different compilers to be compatible they have to agree on all those names, and they never do. Not even different versions of the same compiler can always do that.


问:
How do I explain to non-programers what .NET is?
I don't work at a software company, and I'm one of a small handful of people in the company that know anything about programming. I spend a lot of time automating other programs that are used in the office through public APIs, and I've also created a few stand alone applications. I work almost entirely in C#.NET as every application we seem to use in the office seems to have some form of .NET API.

I've had a few people here ask me about learning "how to program", and where they should start. I think it makes a lot more sense to learn a .NET language as nearly all the programs they would want to automate have a .NET API, and it sounds like VBA is on it's way out and being replaced by VSTA.

However, I'm trying to figure out how to explain what .NET is and why they should learn it to a someone that doesn't know anything about programming. It's not really a language, as there are a number of languages that are considered .NET languages. Plus I think there is a distinction between ".NET" and "The .NET framework" as the latter is more about the libraries provided by Microsoft.

答:
.NET is a framework which can be used by .NET programming languages.  You can use it to write WinForm (non-WPF) desktop apps, WPF desktop apps, Silverlight, ASP.NET, and mobile.  So by learning one part of .NET (such as writing desktop apps), a programmer can pretty easily learn how to write other things such as web apps.

I'm a Java developer and similar things can be said for the Java language, but IMHO, features of Visual Studio and .NET (e.g. Visual Studio's GUI editors & wizards, as well as data binding) makes development in .NET a bit faster and easier.

ContentLicense: CC BY-SA 2.5


问:
how to design a stack without using java library or using list
I have a question how to design a stack without using list or array?

This is one question that I want to think about as I want to better understand stack.

答:
Conceptually speaking, a stack is a linked list without random access and only one point of entry: the top, whereas a list often has random access and two points of entry: the front and the back.
While there usually is a T peek(), peek can't be used for manipulation of the contents. Random access is usually explained as the ability to manipulate at any given point in the collection.

So if you're saying without using a list, do you mean without using a Java API List class as a basis for your work, or really not using a list? The latter is almost impossible, as it basically is a list, and implementing in another manner would be an exercise comparable to making a Rube Goldberg machine.


问:
Differences between Dynamic Dispatch and Dynamic Binding
I've been looking on Google for a clear diffrentiation with examples but couldn't find any.

I'm trying to understand the differences between Dynamic Dispatch and Dynamic Binding in Object Oriented languages.

As far as I understand, Dynamic Dispatch is what happens when the concrete method invoked is decided at runtime, based on the concrete type.

For example:

```<code>public void doStuff(SuperType object){
    object.act();
}
</code>```

SuperType has several subclasses. The concrete class of the object will only be known at runtime, and so the concrete act() implementation invoked will be decided at runtime.

However, I'm not sure what Dynamic Binding means, and how it differs from Dynamic Dispatch.

Please explain Dynamic Binding and how it's different from Dynamic Dispatch. Java examples would be welcome.

答:
Dynamic binding is another name for Late Binding. That's where the language ties a data element or method to an object after compilation time.

Wikipedia equates dynamic & late binding:

Dynamic binding (computing), also known as late binding

links to

http://en.wikipedia.org/wiki/Dynamic_binding_(computing)

Javascript was my first exposure to that, because you can just drop functions into objects willy nilly and do cool things with them.

For example (untested, not guaranteed to work exactly):

```<code>var a = Object();
var do = function() { do something };
a.do = do;
a.do();
// neato!
</code>```

BTW, on a side note, there is some question whether Java is Object-oriented, because one of the original ideas in OO was late binding. Unfortunately, this particular discussion seems to devolve into attempts to define "Object Oriented".

http://c2.com/cgi/wiki?IsJavaObjectOriented

lol!

Under the covers, Dynamic Dispatch and Dynamic Binding may work out the same. But the idea in dynamic dispatch is following some function pointer to see which method to actually invoke, or object to invoke it on. "Binding" is the idea that the method is "bound" to a particular instance (or class of instances) & that's how you identify it.

So they could work together -- a method that's bound to an object with dynamic binding might use dynamic dispatch when you call it.

...

Also dynamic dispatch has more of an OO flavor to it... it's the mechanism behind polymorphism, in which a reference to an object might point to one of multiple implementations. Dynamic dispatch decides at runtime which one to actually run. By contrast, late binding would be dropping in whole new methods that weren't there at compile time.

Body:
Dynamic binding is another name for Late Binding. That's where the language ties a data element or method to an object after compilation time.

Wikipedia equates dynamic & late binding:

Dynamic binding (computing), also known as late binding

links to

http://en.wikipedia.org/wiki/Dynamic_binding_(computing)

Javascript was my first exposure to that, because you can just drop functions into objects willy nilly and do cool things with them.

For example (untested, not guaranteed to work exactly):

var a = Object();
var do = function() { do something };
a.do = do;
a.do();
// neato!

BTW, on a side note, there is some question whether Java is Object-oriented, because one of the original ideas in OO was late binding. Unfortunately, this particular discussion seems to devolve into attempts to define "Object Oriented".

http://c2.com/cgi/wiki?IsJavaObjectOriented

lol!

Under the covers, Dynamic Dispatch and Dynamic Binding may work out the same. But the idea in dynamic dispatch is following some function pointer to see which method to actually invoke, or object to invoke it on. "Binding" is the idea that the method is "bound" to a particular instance (or class of instances) & that's how you identify it.

So they could work together -- a method that's bound to an object with dynamic binding might use dynamic dispatch when you call it.

...

Also dynamic dispatch has more of an OO flavor to it... it's the mechanism behind polymorphism, in which a reference to an object might point to one of multiple implementations. Dynamic dispatch decides at runtime which one to actually run. By contrast, late binding would be dropping in whole new methods that weren't there at compile time.


问:
Which classes should be autowired by Spring (when to use dependency injection)?
I have been using Dependency Injection in Spring for some time now, and I understand how it works and what are some pros and cons of using it. However, when I'm creating a new class I often wonder - Should this class be managed by Spring IOC Container?

And I don't want to talk about differences between @Autowired annotation, XML configuration, setter injection, constructor injection, etc. My question is a general one.

Let's say we have a Service with a Converter:

```<code>@Service
public class Service {

    @Autowired
    private Repository repository;

    @Autowired
    private Converter converter;

    public List<CarDto> getAllCars() {
        List<Car> cars = repository.findAll();
        return converter.mapToDto(cars);
    }
}

@Component
public class Converter {

    public CarDto mapToDto(List<Car> cars) {
        return new ArrayList<CarDto>(); // do the mapping here
    }
}
</code>```

Clearly, the converter doesn't have any dependencies, so it's not necessary for it to be autowired. But for me it seems better as autowired. Code is cleaner and easy to test. If I write this code without DI, the service will look like that:

```<code>@Service
public class Service {

    @Autowired
    private Repository repository;

    public List<CarDto> getAllCars() {
        List<Car> cars = repository.findAll();
        Converter converter = new Converter();
        return converter.mapToDto(cars);
    }
}
</code>```

Now it's much more difficult to test it. Moreover, new converter will be created for every convert operation, even though it's always in the same state, which seems like an overhead.

There are some well known patterns in Spring MVC: Controllers using Services and Services using Repositories. Then, if Repository is autowired (which it usually is), then Service has to be autowired too. And this is quite clear. But when do we use @Component annotation? If you have some static util classes (like converters, mappers) - do you autowire them?

Do you try to make all classes autowired? Then all the class dependencies are easy to inject (once again, easy to understand and easy to test). Or do you try to autowire only when it's absolutely necessary?

I've spent some time looking for some general rules on when to use autowiring, but I couldn't find any specific tips. Usually, people talk about "do you use DI? (yes/no)" or "what type of dependency injection do you prefer", which doesn't answer my question.

I would be grateful for any tips concerning this topic!

答:
Agree with @ericW's comment, and just want to add remember you can use initializers to keep your code compact:

```<code>@Autowired
private Converter converter;
</code>```

or

```<code>private Converter converter = new Converter();
</code>```

or, if the class really has no state at all

```<code>private static final Converter CONVERTER = new Converter();
</code>```

One of the key criteria for whether Spring should instantiate and inject a bean is, is that bean so complicated that you want to mock it in testing? If so, then inject it. For example, if converter makes a round trip to any external system, then make it a component instead. Or if the return value has a big decision tree with dozens of possible variations based on the input, then mock it. And so forth.

You've already done a good job of rolling up that functionality and encapsulating it, so now it's just a question of whether it's complex enough to be considered a separate "unit" for testing.

Body:
Agree with @ericW's comment, and just want to add remember you can use initializers to keep your code compact:

@Autowired
private Converter converter;

or

private Converter converter = new Converter();

or, if the class really has no state at all

private static final Converter CONVERTER = new Converter();

One of the key criteria for whether Spring should instantiate and inject a bean is, is that bean so complicated that you want to mock it in testing? If so, then inject it. For example, if converter makes a round trip to any external system, then make it a component instead. Or if the return value has a big decision tree with dozens of possible variations based on the input, then mock it. And so forth.

You've already done a good job of rolling up that functionality and encapsulating it, so now it's just a question of whether it's complex enough to be considered a separate "unit" for testing.


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
You are, of course, getting a really skewed sample here, and you might do better to do your own research on your own site.

I, personally, use NoScript.  I'm rarely reluctant to whitelist a site, but it does have to appear worth my while to do so.  (In other words, I need a reason, but it doesn't have to be very convincing.)


问:
Why would I want a UnitOfWork layer if my service/business logic layer is specific enough?
I'm getting into the Repository pattern (which I love), and as I read up on it I see this UnitOfWork pattern in many articles. Before I knew anything about UnitOfWork I was just using my Repository pattern inside my service layer (business logic). This seems to work great so I'm wondering why having another layer (ie. UnitOfWork) may be beneficial?

Why would I want a UnitOfWork layer in my service/business logic layer? If your service layer is specific enough and doesn't cover everything under the sun then it doesn't seem like it's needed.

Note that I'm looking at this from an EF perspective. I've even read articles where people mention that EF's DbContext is a UnitOfWork. So why make my own UnitOfWork if EF's DbContext already does this for me? Why not create my DbContext in my service layer and then pull in the repositories I need and do all good?

The Repository I get because it makes testing my services easier, but I don't see the benefit of a UnitOfWork especially if you are using an ORM.

答: If you are a 100% sure you won't change your ORM in the future then no need to use UOW, EF does it for you, but if there is a need to change your ORM in the future, (for example if you will need dynamic tables creation, or an ORM that is more performant than EF) if you have a UOW layer that abstracts away your DbContext , you will find it easy to change the ORM.</p>


问:
Method naming advice required
My question will be about how do you think it would be fit to name some methods in a fluent interface. Let me try to demonstrate the problem.

Consider this relation tree:

A person can have dogs and cats, and a dog can have bones. Pretty simple.

What i'm trying to do is create a domain specific fluent interface for determining, which ones of these relations does the user need. It is able to handle any depth of relationships.

I designed the operation something like this (It is building the assoicaiton tree, from which i can determine, what the user wants):

As code (it may be more readable):

```<code>personAssoc = person.associate().withCats().and().withDogs().withBones().up().done();
</code>```

But i'm trying to make this part as intuitive as possible, so i wan't the method names to make sense after each other, and be as close to spoken language as possible. My biggest concerns are the following 3 method names:

and() in my language of choice and is a reserved keyword, so i can't use it. I looked up synonyms (together(), including(), also()) but they don't sound/look right  (and means, that we will add more children to the parent association).

up() it is obviously breaking any kind of flow. With this method name, the whole thing became a lot further away from spoken language, than i wanted to (up means, we are not necessary wan't to add more relations to the parent, but we are done with the current one. In code it is the same as and).

done() is only called once, at the end of the method calls, but still doesn't fit the picture (done means, that we are literally done, we won't add more associations).

What i'm looking for is other, better names for the above 3, which:

Which make the usage of the fluent interface closer to spoken language.

For and a name, which is as far as possible from any language keywords.

If you read this whole thing, feel free to drop by any ideas, it might help me out a great deal!
Thank you for any suggestion.

答:
your proposed method just doesn't look maintainable to me

it's much easier to give Person a addCat and addDog method that does just that

```<code>Dog dog = new Dog();
dog.addBone();
person.addDog(dog);
</code>```

this way you can also create the dog with its bones somewhere else without passing person to the bone factory.

Title: Method naming advice required

Body:
your proposed method just doesn't look maintainable to me

it's much easier to give Person a addCat and addDog method that does just that

Dog dog = new Dog();
dog.addBone();
person.addDog(dog);

this way you can also create the dog with its bones somewhere else without passing person to the bone factory.


答:
well, "with" is a awkward name... "has" is a much better one. Has and Is are very well established terms, as is Get. You should use those terms as it makes discoverability easier - people are familiar with GetParent for example as returning a parent object. This makes it a good term to keep using.

'And' seems to be "return parent", but in your naming convention, might be better described as "owner", so getOwner() or whoseOwner() might fit better.

Then you have

```<code>person.associate().hasCats().whoseOwner().hasDogs().hasBones().whoseOwner().disassociate()
</code>```

disassociate seems like the opposite of associate - but both are artificial terms, it might be better to choose something less 'in keeping' with the tree and use a term that says "start processing" or similar, so you know its part of the plumbing.

Title: Method naming advice required

Body:
My question will be about how do you think it would be fit to name some methods in a fluent interface. Let me try to demonstrate the problem.

Consider this relation tree:

A person can have dogs and cats, and a dog can have bones. Pretty simple.

What i'm trying to do is create a domain specific fluent interface for determining, which ones of these relations does the user need. It is able to handle any depth of relationships.

I designed the operation something like this (It is building the assoicaiton tree, from which i can determine, what the user wants):

As code (it may be more readable):

```<code>personAssoc = person.associate().withCats().and().withDogs().withBones().up().done();
</code>```

But i'm trying to make this part as intuitive as possible, so i wan't the method names to make sense after each other, and be as close to spoken language as possible. My biggest concerns are the following 3 method names:

and() in my language of choice and is a reserved keyword, so i can't use it. I looked up synonyms (together(), including(), also()) but they don't sound/look right  (and means, that we will add more children to the parent association).

up() it is obviously breaking any kind of flow. With this method name, the whole thing became a lot further away from spoken language, than i wanted to (up means, we are not necessary wan't to add more relations to the parent, but we are done with the current one. In code it is the same as and).

done() is only called once, at the end of the method calls, but still doesn't fit the picture (done means, that we are literally done, we won't add more associations).

What i'm looking for is other, better names for the above 3, which:

Which make the usage of the fluent interface closer to spoken language.

For and a name, which is as far as possible from any language keywords.

If you read this whole thing, feel free to drop by any ideas, it might help me out a great deal!
Thank you for any suggestion.

Body:
well, "with" is a awkward name... "has" is a much better one. Has and Is are very well established terms, as is Get. You should use those terms as it makes discoverability easier - people are familiar with GetParent for example as returning a parent object. This makes it a good term to keep using.

'And' seems to be "return parent", but in your naming convention, might be better described as "owner", so getOwner() or whoseOwner() might fit better.

Then you have

person.associate().hasCats().whoseOwner().hasDogs().hasBones().whoseOwner().disassociate()

disassociate seems like the opposite of associate - but both are artificial terms, it might be better to choose something less 'in keeping' with the tree and use a term that says "start processing" or similar, so you know its part of the plumbing.


答:
There are two issues here: good naming, and the abuse of fluent interfaces.

A good API has two jobs: It must be straightforward to write code using this API, and the function of the resulting code should be obvious to a reader. While fluent interfaces excel in the latter matter, languages that try to be overly English-like fail the former requirement. Any API is a language that has to be learnt, so it should be as unsurprising as possible in order for a user to learn quickly.

I would therefore suggest that you do use a fluent API, but toned down to handle only one level of hierarchy at a time:

```<code>Person p = makePerson()
  .with(makeDog().with(makeBone()))
  .with(makeCat())
  .finish();
</code>```

where PersonBuilder#with is overloaded to handle arguments of types Dog, DogBuilder, Cat, and CatBuilder etc.

If you absolutely must use a single level, I would like to suggest end, finish, or back instead of and. Using proper indentation would also help in making the code clearer:

```<code>person.associate()
  .withDog()
     .withBone()
     .end()
  .end()
  .withCat()
  .end()
.end()
</code>```

This does not make it more English-like, but it follows clear rules (any with is mirrored by an end) and looks familiar to any programmer (and especially to anyone who has seen Ruby).

Title: Method naming advice required

Body:
There are two issues here: good naming, and the abuse of fluent interfaces.

A good API has two jobs: It must be straightforward to write code using this API, and the function of the resulting code should be obvious to a reader. While fluent interfaces excel in the latter matter, languages that try to be overly English-like fail the former requirement. Any API is a language that has to be learnt, so it should be as unsurprising as possible in order for a user to learn quickly.

I would therefore suggest that you do use a fluent API, but toned down to handle only one level of hierarchy at a time:

Person p = makePerson()
  .with(makeDog().with(makeBone()))
  .with(makeCat())
  .finish();

where PersonBuilder#with is overloaded to handle arguments of types Dog, DogBuilder, Cat, and CatBuilder etc.

If you absolutely must use a single level, I would like to suggest end, finish, or back instead of and. Using proper indentation would also help in making the code clearer:

person.associate()
  .withDog()
     .withBone()
     .end()
  .end()
  .withCat()
  .end()
.end()

This does not make it more English-like, but it follows clear rules (any with is mirrored by an end) and looks familiar to any programmer (and especially to anyone who has seen Ruby).


问:
How to handle unexpected schema changes to production database
Is it a common or normal practice to encounter schema changes, especially renamed or removed columns, in a production database, without having been notified of the change?  If unexpected schema changes are anticipated in the production database, how are they guarded against, other than basic exception handling?

I've worked mainly with credit union software, DoD software, high volume e-commerce web applications, real estate systems, robotics, and more recently CMMS, GIS, and SCADA systems.  Although the '90s and early 2000s were more of the wild west, everything I have been involved with over the last 10 years or so has required change management.  Modifications to a production database without change control is not allowed by policy and by security controls.

Comments in the accepted answer to this question - Why is “Select * from table” considered bad practice make me wonder how much of this is academic and how much is reality.

答:
The short answer: Log it, maybe notify the user, and maybe continue execution of your application.

Changes happen all the time. In production. Without warning. Often by mistake.

Even with change control policies carved in stone, mistakes happen. A DBA that is tuning a query drops a table. A developer with too much access accidentally removes a column. One of the DBAs moves your tables to a different schema. A database becomes corrupted.

These are some of the things that I have seen occur in live production databases over the years. Each one made me very glad there were backups of the production applications.

There will always be something somewhere that goes wrong. That is one of the reasons that you have error handling code in production applications: to prevent the failure of one section of code from causing the overall failure of all of it.

Errors

Log everything that is an error with the most details you can. Include the full error message (where possible). Make sure that your code can gracefully shutdown when an error is sufficiently detrimental to require it. And log that your app forcefully terminated itself. Displaying errors to the user is something that you should do in most, but not all circumstances.

Warnings

Log warnings, but only grab the relevant minimum information you need to diagnose and correct the issue. You may want to set some flag that will conditionally allow you to log warnings (and/or informational messages). This will help in keeping the log file small. Warning messages are mostly something that you will want to show to the user, especially when the user can make changes to correct the issue.

Informational Messages

Only log informational items when you need normally unimportant information. In production code, I have found it useful for informational messages to include when you enter and leave a function, method, properties (when they do more that get/put values), start up and shut down singleton instances (e.g., SerialPort). These informational messages do not need to be shown to the user.


答:
Ideally, NO unexpected changes happen to a production system, EVER.

In reality of course, they happen all the time.

The way you handle it is by having proper procedures in place to minimise them, AND having proper procedures in place to deal with them when they happen (lists of people to call, things to check, rollback processes, etc. etc..

Risk can also be reduced by properly testing all changes that are scheduled as good as you can, in a situation as close as possible to the life system (identical hardware and software configuration for example), then having procedures in place that make it imperative that no manual changes are performed to production systems except those listed explicitly in the upgrade/installation manuals for your product.

Notice there's not a single piece of monitoring software, no coding practice, nothing technical in there. It's all procedural and documentation.

Combine that with proper access control to production systems (basically only the people who do installations and disaster recovery have write access there, and by procedure they only log in with those specific accounts when performing those specific tasks), and you've done all you can.

Only thing to remain to do in your code is to make it as robust as you can towards schema changes.

Of course you can't guard against a column you need being deleted or having its data type made narrower. But you can guard against a column changing to NOT NULL by ensuring all columns are always written with values, and you can guard against most column additions (obviously not NOT NULL columns) by writing your code so as to only retrieve and write explicit columns, only the minimum set you need for your operations.

Title: How to handle unexpected schema changes to production database

Body:
Is it a common or normal practice to encounter schema changes, especially renamed or removed columns, in a production database, without having been notified of the change?  If unexpected schema changes are anticipated in the production database, how are they guarded against, other than basic exception handling?

I've worked mainly with credit union software, DoD software, high volume e-commerce web applications, real estate systems, robotics, and more recently CMMS, GIS, and SCADA systems.  Although the '90s and early 2000s were more of the wild west, everything I have been involved with over the last 10 years or so has required change management.  Modifications to a production database without change control is not allowed by policy and by security controls.

Comments in the accepted answer to this question - Why is “Select * from table” considered bad practice make me wonder how much of this is academic and how much is reality.


问:
The problem of dependencies management
Let's consider the next situation:

We have a module A which has a class Crt570 intended to interact with a device.

We have a module B which uses Crt570 in the class called M100Communicator.

We have two applications C and D and both of them wants to use module B.

Application D wants to use B, but doesn't want to use Crt570 and reference module A, therefore.

"Module" here means dll.

So we decided to extract an interface from Crt570 and called it ICrt570.
But what to do with that now? It's just very strange to move ICrt570 into the domain module (let's call it module E) or somewhere else because after that Crt570 has to reference the module which will contain ICrt570!

How to solve the puzzle?

UPDATE
In order to make the question more clear for readers in the future I'll add a bit more details.

Module A is the dll which contains nothing but Crt570 class (with it's infrastructure). So this dll is dedicated to manage a device absolutely, nothing more.

Module B is the dll which contains models specific for several applications in our domain.
At least 3 applications want to use this module and they, of course, don't want to pull dll's they don't need.

One of the models that C and D apps want to use is the M100Communicator model. And, in particular, this class (M100Communicator) depends on module A (Crt570 class).

Module E which I mentioned is a domain module. It contains many classes and interfaces, so module A doesn't want to use it, apparently.

答:
As david.pfx writes in his comment, there is a bit of info missing, but I am willing to give it a shot.

I am making an assumption in my answer.

The reason that C and D both want to use B is, at least in part, to use M100Communicator

Thereafter it kinda depends on if other modules are around that want to use the ICrt570 interface.

Scenario A

If it is only module B that needs to interact with your interface, you could define it there. Then the two C and D, could give M100Communicator each an implementation of ICrt570.

C References A and B Giving Crt570 from A to M100Communicator as the implementation of ICrt570 to be used. (A would also have to reference B since it is implementing an interface defined there)

D References only B. Since M100Communicatorneeds an ICrt570implementation it still has to supply this. Either it has to make an implementation itself or reference another module with an implementation.

Scenario B

If, on the other hand other modules than B are going to have a dependency on ICrt570, then you would need to move it to some other module, maybe even its own.

You could define the module Eas you mention, containing ICrt570. This module's reason for living is to be the "Device communications interface module". This module defines interfaces, nothing else.

Then all the others can reference this module: A to implement the interface, Bto have a dependency on it. C and D so they know what ICrt570 is. Since this module is only interfaces there isn't much "harm" in referencing it.

C and D are now free to choose whichever implementation of ICrt570 that they want. Same goes for X, Y, Z who also use ICrt570 in some way.

A couple of points

References are not necessarily bad, only if the modules you reference have a lot of different stuff you don't want. Then you might have a problem with The Single Responsibility Principle, your modules might be doing too much.

Something that helped me better understand dependency management with low coupling, was to study the Onion Architecture by Jeffrey Palermo. He takes the whole thing very far, some might say too far. But the principles of low coupling, dependency injection etc. are explained very well in his blog posts.

Title: The problem of dependencies management


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
This is what I would do.

Mirror the site.

Any ability to take down the site may be hindered by the fact that you no longer host the site, so let's put it back into your complete control. So set up another account with the same domain as your client and have the domain forwarded from his Cpanel to your mirrored site. Once you've successfully forwarded web traffic  to the mirrored site, remove ALL your content from his hosting platform. (Don't transfer the domain, as it may interupt email communications, just forward.) He won't be able to tell the difference from the frontend, but you will have complete control of the site and be able to carry out your shut down.

( Just noticed @Sam mentioned this option as well, it's a good way to put the ball back in your court )

Apply Pressure, but be flexible

@Walter Suggested the two best non-legal routes prior to an all out take down. Talk to your friend about the situation. Offer a payment plan for him to pay you back over a time period. If he resists or fails to pay in a reasonable amount of time (at this point) then...

Go Rambo in Court

Last resort, legal route. Starting with small claims @DanRay provides this step. Basically present your case and be sure to use email correspondence in your case. Off the premise that he does not own the materials that you provided and that he's using them, you'll be able to make the case that you've incurred damages as a result of non payment. You can claim that the site was not intended to be released until you were compensated and that the current site is not a legitimate use of your work.

I would always suggest having a lawyer present the case (even in small claims). Don't waste time trying to win and just win it. You've got a case, even without a contract. Make it clear to your representation that you intend to make it  You're getting bullied, make it his loss.

Future Prospects

For the future, contracts are fantastic -- but understandably awkward for 'friend' contacts. Good call on letting him have his own hosting platform, but do the development on your hosting and push it to your client's platform when you're done (and paid) and not a moment sooner ;]

GOOD LUCK!

Title: How to get money from reluctant client?


问:
Using the Decorator pattern to add public methods to an object
The Decorator pattern is usually used to extend the functionality of an object by extending one of it's current methods.

To illustrate, please consider an object object and a decorator decorator. object has one method called methodA(). decorator, because we're in the Decorator pattern, also has this method by inheritance (both object and decorator eventually inherit from the same super-class which has methodA(). Let's call it AbstractObject).

methodA() in object looks like this:

```<code>public void methodA(){
    // do stuff
}
</code>```

methodA() in decorator looks like this:

```<code>public void methodA(){
    // do some extra stuff.
    wrappedObject.methodA(); // and then delegate to the wrapped object.
}
</code>```

It would be used like this:

```<code>AbstractObject object = new ConcreteObject();
object.methodA(); // does stuff
object = new ConcreteDecorator(object);
object.methodA(); // does stuff and some more stuff. the extended methodA().
</code>```

The point of decorator is to extend the functionality of object, and it does this by extending one of object's current methods. So far, classic Decorator.

Now, my question:

As I said Decorator usually extends an object's functionality by adding content to one of the object's current methods.

But what if I wanted to use Decorator to add public methods to an object?

Please consider the following scenario where decorator has another method methodB():

```<code>AbstractObject object = new ConcreteObject();
object.methodA(); // does stuff
object = new ConcreteDecorator(object);
((ConcreteDecorator)object).methodB();
// methodB() belongs to ConcreteDecorator() but not to AbstractObject().
</code>```

As you see if I wanted to do this, I would have to cast object to ConcreteDecorator.

This exposes the concrete type of object and the fact that it's decorated, and as such somewhat defeats the intent of the Decorator pattern. Also, the code invoking methodB() would have to know object is decorated. Again, not very much in the spirit of Decorator.

In light of this I have two questions:

Is the Decorator pattern ever used this way? Is it ever used to add
public methods to an object, as opposed to only 'extending' it's
current methods?

Are there situations where this would be a good idea or a wise use of
Decorator?

答:
The decorator pattern is typically used to avoid an explosion of subclasses.  A common example involves UI windows that you may want to have any combination of n attributes (scrollbar, titlebar, resizable, movable, etc.).

Supporting all combinations of all those N attributes for all UI windows M subclasses would involve making N * M subclasses.

The decorator pattern prevents the explosion by wrapping around the base window class' existing public methods.

The decorator pattern ideally would only require N + M classes in this case.

For the case you have described, you are adding new public methods; therefore, the decorator pattern probably is not ideal.  I cannot think of any situations where it would be ideal to add new methods via a decorator.

A few alternatives to consider:

Subtyping

It is valid to use subtyping to add methods, provided you are keeping the SOLID principles in mind.  Therefore, you might consider extending the concrete object to support methodB and then design the decorator around it.

```<code>AbstractObject object = new ExtendedConcreteObject();
object.methodA(); // does stuff
object = new ConcreteDecorator(object);
(ConcreteDecorator)object.methodB();
// methodB() belongs to ExtendedConcreteObject() but not to AbstractObject()
</code>```

Adapter Pattern

Another way to view the problem:  by adding a public method, you are changing the object's interface.  This can be done by using the adapter pattern.  To keep the concrete decorator simple, you might consider creating a decorator and then building an adapter for that decorator.

```<code>AbstractObject object = new ConcreteObject();
object.methodA(); // does stuff
object = new ConcreteDecorator(object);
object = new ConcreteAdapter(object);
(ConcreteAdapter)object.methodB();
// methodB() belongs to ConcreteAdapter() but not to AbstractObject() or ConcreteDecorator().
</code>```

Body:
The decorator pattern is typically used to avoid an explosion of subclasses.  A common example involves UI windows that you may want to have any combination of n attributes (scrollbar, titlebar, resizable, movable, etc.).

Supporting all combinations of all those N attributes for all UI windows M subclasses would involve making N * M subclasses.

The decorator pattern prevents the explosion by wrapping around the base window class' existing public methods.

The decorator pattern ideally would only require N + M classes in this case.

For the case you have described, you are adding new public methods; therefore, the decorator pattern probably is not ideal.  I cannot think of any situations where it would be ideal to add new methods via a decorator.

A few alternatives to consider:

Subtyping

It is valid to use subtyping to add methods, provided you are keeping the SOLID principles in mind.  Therefore, you might consider extending the concrete object to support methodB and then design the decorator around it.

AbstractObject object = new ExtendedConcreteObject();
object.methodA(); // does stuff
object = new ConcreteDecorator(object);
(ConcreteDecorator)object.methodB();
// methodB() belongs to ExtendedConcreteObject() but not to AbstractObject()

Adapter Pattern

Another way to view the problem:  by adding a public method, you are changing the object's interface.  This can be done by using the adapter pattern.  To keep the concrete decorator simple, you might consider creating a decorator and then building an adapter for that decorator.

AbstractObject object = new ConcreteObject();
object.methodA(); // does stuff
object = new ConcreteDecorator(object);
object = new ConcreteAdapter(object);
(ConcreteAdapter)object.methodB();
// methodB() belongs to ConcreteAdapter() but not to AbstractObject() or ConcreteDecorator().

ContentLicense: CC BY-SA 4.0


答:
Decoration is about adding subtle behavioural changes to an underlying class.

I think your intention is to actually Extend a class. Think "Separation of Concerns".  Also, the "Open/Closed" principle springs to mind (which I personally don't entirely agree with)

The point of decoration is that you pass an object around which supports a given interface.  If you're doing extra stuff in extra methods, then your application will need to "down-cast" that object to get the extra behavior.

Downcasting to some engineers seems okay, while other engineers feel this isn't a clean solution as code is littered with instanceof keywords.   This ties classes to your extended implemetation which requires more diligence when refactoring.

Personally, downcasting of objects should be used sparingly, and should be hidden as much as possible from consuming classes, as it breaks an interface.

All I am saying is it really is a subjective question.  Be careful.

Title: Using the Decorator pattern to add public methods to an object

Body:
The Decorator pattern is usually used to extend the functionality of an object by extending one of it's current methods.

To illustrate, please consider an object object and a decorator decorator. object has one method called methodA(). decorator, because we're in the Decorator pattern, also has this method by inheritance (both object and decorator eventually inherit from the same super-class which has methodA(). Let's call it AbstractObject).

methodA() in object looks like this:

```<code>public void methodA(){
    // do stuff
}
</code>```

methodA() in decorator looks like this:

```<code>public void methodA(){
    // do some extra stuff.
    wrappedObject.methodA(); // and then delegate to the wrapped object.
}
</code>```

It would be used like this:

```<code>AbstractObject object = new ConcreteObject();
object.methodA(); // does stuff
object = new ConcreteDecorator(object);
object.methodA(); // does stuff and some more stuff. the extended methodA().
</code>```

The point of decorator is to extend the functionality of object, and it does this by extending one of object's current methods. So far, classic Decorator.

Now, my question:

As I said Decorator usually extends an object's functionality by adding content to one of the object's current methods.

But what if I wanted to use Decorator to add public methods to an object?

Please consider the following scenario where decorator has another method methodB():

```<code>AbstractObject object = new ConcreteObject();
object.methodA(); // does stuff
object = new ConcreteDecorator(object);
((ConcreteDecorator)object).methodB();
// methodB() belongs to ConcreteDecorator() but not to AbstractObject().
</code>```

As you see if I wanted to do this, I would have to cast object to ConcreteDecorator.

This exposes the concrete type of object and the fact that it's decorated, and as such somewhat defeats the intent of the Decorator pattern. Also, the code invoking methodB() would have to know object is decorated. Again, not very much in the spirit of Decorator.

In light of this I have two questions:

Is the Decorator pattern ever used this way? Is it ever used to add
public methods to an object, as opposed to only 'extending' it's
current methods?

Are there situations where this would be a good idea or a wise use of
Decorator?


问:
Clarify the Open/Closed Principle
As I have had it explained, the open/closed principle states that once written code should not be modified (aside from bug fixes). But if my business rules change shouldn't I modify the code implementing those changes? I suspect I'm not understanding something about how the principle because it doesn't make sense to me.</p>

答:
Personally I think this principle should be taken with a pinch of salt.  Code is organic, businesses change and code changes according to the needs of a business as time goes on.

I find it very difficult to get my head around the fact that abstraction is key.  What if the abstraction was originally wrong?  What if the business function has changed significantly?

This principle essentially ensures that ORIGINAL intentions and behavior of a design must never change.  That probably works for those who have public API's and their clients have trouble keeping up with new releases, and some other edge-cases.   However, if a company owns ALL the code, then I challenge this principle.

Having good test coverage of your code should make refactoring your code base a breeze.  It means that it's okay to get stuff wrong - your tests will help guide you to a better design.

Saying that, if there aren't any tests, then this principle is sound.

Title: Clarify the Open/Closed Principle


问:
Types of unit tests based on usefulness
From value point of view I see two groups of unit tests in my practice:

Tests that test some non-trivial logic. Writing them (either before
implementation or after) reveals some problems/potential bugs and
helps to be confident in case logic is changed in the future.

Tests that test some very trivial logic. Those tests more like
document code (typically with mocks) than test it. The maintenance
workflow of those tests is not "some logic changed, test became red - thanks God I wrote this test" but "some trivial code changed, test became false negative - I have to maintain (rewrite) the test
without gaining any profit". Most of the time those tests are not
worth maintaining (except religious reasons). And according to my
experience in many systems those tests are like 80% of all tests.

I am trying to find out what other guys think on the topic of unit tests separation by value and how it corresponds to my separation. But what I mostly see is either fulltime TDD propaganda or tests-are-useless-just-write-the-code propaganda. I'm interested in something in the middle. Your own thoughts or references to articles/papers/books are welcome.

答:
What is a unit test, really? And is there really such a big dichotomy in play here?

We work in a field where reading literally one bit past the end of a buffer can totally crash a program, or cause it to produce a totally inaccurate result, or as evidenced by the recent "HeartBleed" TLS bug, lay a supposedly secure system wide open without producing any direct evidence of the flaw.

It is impossible to eliminate all complexity from these systems. But our job is, to the extent possible, to minimize and manage that complexity.

Is a unit test a test that confirms, for example, that a reservation is successfully posted in three different systems, a log entry is created and an Email confirmation is sent out?

I'm going to say no. That's an integration test. And those most definitely have their place, but they're also a different topic.

An integration test works to confirm the overall function of an entire "feature." But the code behind that feature should be broken down into simple, testable building blocks, aka "units."

So a unit test should have a very limited scope.

Which implies that the code tested by the unit test should have a very limited scope.

Which further implies that one of the pillars of good design is to break your complex problem down into smaller, single-purpose pieces (to the extent possible) which can be tested in relative isolation from one another.

What you end up with is a system made out of reliable foundation components, and you know if any of those foundational units of code break because you have written simple, small, limited-scope tests to tell you exactly that.

In many cases you should also probably have multiple tests per unit. The tests themselves should be simple, testing one and only one behavior to the extent possible.

The notion of a "unit test" testing non-trivial, elaborate, complex logic is, I think, a bit of an oxymoron.

So if that kind of deliberate design break-down has taken place, then how in the world could a unit test suddenly start producing false positives, unless the basic function of the tested code unit has changed? And if that has happened, then you better believe there are some non-obvious ripple effects in play. Your broken test, the one that seems to be producing a false positive, is actually warning you that some change has broken a wider circle of dependencies in the code base, and it needs to be examined and fixed.

Some of those units (many of them) may need to be tested by using mock objects, but that doesn't mean you have to write more complex or elaborate tests.

Going back to my contrived example of a reservation system, you really can't be sending requests off to a live reservation database or third-party service (or even a "dev" instance of it) every time you unit test your code.

So you use mocks which present the same interface contract. The tests can then validate the behavior of a relatively small, deterministic chunk of code. Green all down the board then tells you that the blocks that comprise your foundation aren't broken.

But the logic of the individual unit tests themselves remains as simple as possible.

Title: Types of unit tests based on usefulness


答:
This is of course, just my oppinion, but having spent the last few months learning functional programming in fsharp (coming from a C# background) has made me realize a few things.

As the OP stated, there are typically 2 types of "unit tests" we see day to day. Tests that cover the in's and out's of a method, which are generally the most valuable, but are hard to do for 80% of the system which is less about "algorithims" and more about "abstractions".

The other type, is testing abstraction interactivity, typically involve mocking. In my oppinion, this tests are mostly necessary due to the design of your application. Ommiting them, and you risk weird bugs and spagetti code, because people don't think about their design properly unless they are forced to do the tests first (and even then, usually mess it up). The problem is not so much the testing methodology, but the underlying design of the system. Most systems built with imperative or OO languages have an inhert reliance on "side effects" aka "Do this, but don't tell me anything". When you rely on the side effect, you need to test it, because a business requirement or operation is usually a part of it.

When you design your system in a more functional way, where you avoid building dependencies on side-effects and avoid state changes/tracking through immutability, it enables you to focus more heavily on "ins and outs" tests, which clearly test more the action, and less how you get there. You will be amazed what things like immutability can give you in terms of much simpler solutions to the same problems, and when you are no longer dependent on "side-effects" you can do things like parallelizing and asynchronous programming with almost no additional cost.

Since I started coding in Fsharp, I have not needed a mocking framework for anything, and have even shed my dependency altogether on an IOC Container. My tests are driven by business need and value, and not on heavy abstraction layers typically needed to achieve composition in imperative programming.

Title: Types of unit tests based on usefulness

Body:
From value point of view I see two groups of unit tests in my practice:

Tests that test some non-trivial logic. Writing them (either before
implementation or after) reveals some problems/potential bugs and
helps to be confident in case logic is changed in the future.

Tests that test some very trivial logic. Those tests more like
document code (typically with mocks) than test it. The maintenance
workflow of those tests is not "some logic changed, test became red - thanks God I wrote this test" but "some trivial code changed, test became false negative - I have to maintain (rewrite) the test
without gaining any profit". Most of the time those tests are not
worth maintaining (except religious reasons). And according to my
experience in many systems those tests are like 80% of all tests.

I am trying to find out what other guys think on the topic of unit tests separation by value and how it corresponds to my separation. But what I mostly see is either fulltime TDD propaganda or tests-are-useless-just-write-the-code propaganda. I'm interested in something in the middle. Your own thoughts or references to articles/papers/books are welcome.


问:
Is byte stuffing required when using a packet field length
I'm involved in a project which involves implementing a binary protocol that will be transmitted over TCP.  During our early discussions we have hit a brief snag on deciding whether byte stuffing is required if we decide to include the packet length in the field header.

For example.  If our packet structure was like so:

```<code>[STX] [PACKET LENGTH] [PACKET ID] ..... [ETX]
</code>```

Do we need to byte stuff?  One of my colleagues seems to say that given we know the packet length then even if a special character i.e. STX, ETX appears in the bytes it will not matter as we are reading [Packet length] amount of bytes anyway.

Seems to make sense but I'm not 100% sure if that reasoning is quite right.

Please note that we are not using existing protocol handler type modules such as proto-buf but designing this protocol ourselves for our own use.

To confirm what I think I'm meaning when referring to byte stuffing:

Byte stuffing is a process that transforms a sequence of data bytes
  that may contain 'illegal' or 'reserved' values into a potentially
  longer sequence that contains no occurrences of those value

Taken from Wiki - Consistent Overhead Byte Stuffing

答:
I had to look up "byte stuffing." I'm not sure its a common term so you might want to include a short definition of it.

Assuming that you mean the technique that modifies bytes so that you can have a terminating byte, such as zero, by escaping the data bytes that are zero...

Please, think about this before asking. Field length. Terminating character. Can you think of any situation that would require both?

The field length is almost always the best choice. After reading the length you can read the data. No need to check the data for special bytes.

One word of caution though: Don't blindly trust the length data. Always check that the value is in a valid range first.


答:
Your colleague is correct.

If you have total packet length, and the data payload is the only variable-length piece in the packet, then you do not need to byte stuff the payload.  If you have more than one variable-length piece, you will have to think about how you will disambiguate the various chunks, so you know where one stops and the next begins.

Byte stuffing is used when it is not feasible to insert the packet length into the stream before the packet data payload.  USUALLY, this is because messages are of varying lengths and the  message length cannot be known a priori.

Title: Is byte stuffing required when using a packet field length

Body:
I'm involved in a project which involves implementing a binary protocol that will be transmitted over TCP.  During our early discussions we have hit a brief snag on deciding whether byte stuffing is required if we decide to include the packet length in the field header.

For example.  If our packet structure was like so:

```<code>[STX] [PACKET LENGTH] [PACKET ID] ..... [ETX]
</code>```

Do we need to byte stuff?  One of my colleagues seems to say that given we know the packet length then even if a special character i.e. STX, ETX appears in the bytes it will not matter as we are reading [Packet length] amount of bytes anyway.

Seems to make sense but I'm not 100% sure if that reasoning is quite right.

Please note that we are not using existing protocol handler type modules such as proto-buf but designing this protocol ourselves for our own use.

To confirm what I think I'm meaning when referring to byte stuffing:

Byte stuffing is a process that transforms a sequence of data bytes
  that may contain 'illegal' or 'reserved' values into a potentially
  longer sequence that contains no occurrences of those value

Taken from Wiki - Consistent Overhead Byte Stuffing


答: One thing to consider asking a lawyer is if there's any potential legal liability for the hosting company.  You can always complain about your client to the hosting company, but they're very unlikely to do anything unless there's potential liability.  At least in the US, some companies are liability-averse.  In the UK, I don't know.  There isn't a DMCA takedown notice you can send them, and I don't know if there's a credible threat.</p>

Title: How to get money from reluctant client?

Body:
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.


问:
DRY code, DRY tests?
At some point I had to create some class "Class1" and that class needs a method "method". So I have the following:

```<code>Class1MethodTest: A total of N tests that check the behavior of Class1.method
Class1 method: A full implementation of the method
</code>```

But a bit later I need a different class "Class2" to have a completely similar method "method". Now I have several approaches:

Approach 1

```<code>Class1MethodTest: A total of N tests
Class1 method: Full implementation
Class2MethodTest: Another set of identical tests
Class2 method: Another full implementation
</code>```

Pros: Stupid simple

Cons: not DRY

At least that's the first attempt and I might even write this before doing any refactoring, right?

Approach 2:

```<code>_hidden_private_implementation_function: Full implementation of required method
Class1MethodTest: A total of N tests
Class1 method: Call hidden_private_whatever
Class2MethodTest: Another set of identical tests
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY code, still stupid simple

Cons: Tests aren't DRY, "Test interface, not implementation"

Approach 3:

```<code>MethodTest: A total of N tests
TotallyPublicCommonMethod: Full implementation of required method
Class1MethodTest: Just one test to verify that Class1 method calls the Public one
Class1 method: Call public common method
Class2MethodTest: One more test
Class2 method: Also call common method
</code>```

Pros: DRY, stupid simple

Cons: .. any other than "You're testing implementation, not interface"?

Approach 4:

This is where it gets a bit exotic. Python allows me to DRY the "Approach 3" directly:

```<code>_hidden_private_implementation_function: Full implementation of required method
makeTestForClass(cls): return a total of N tests for class cls
Class1MethodTest = makeTestForClass(Class1)
Class1 method: Call hidden_private_whatever
Class2MethodTest = makeTestForClass(Class2)
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY, "Don't test implementation"

Cons: Not that simple. Too hard to modify if I ever decide to change something in Class1.method, but not Class2.method

I can think of a couple more approaches but those are not very different from these above.

Right now I have some code looking something like "Approach 1" and I am thinking on which way I should go next to make it all cleaner and better.

答:
You're right when you tell that you may use the first approach before refactoring. While personally, I disagree with this approach, that's the rule of three from Refactoring by Martin Fowler (page 58):

Here's a guideline Don Roberts gave me: The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor.

It remains that the duplication in code is annoying. From here, you have to think about the exact context of the duplication:

Either two classes are related (for example both Cat and Dog can be fed, and it takes the same steps to feed them both, except the food which will change), in which case, create an inheritance (in my example, a parent class Pet),

Or two classes are unrelated, and just rely on the same method. For example, WebRequest class may rely on GetSlug¹ to find the slug of the current request; Customer may also rely on GetSlug to normalize the name of the customer for further search purposes. However, WebRequest and Customer are totally unrelated, and it makes no sense to create a common object for those classes.

Here, the solution would be to call a common method from those two classes, by instantiating the third class containing this method. For example, both RequestUri and CustomerName may become objects implementing ISlug interface.

In unit tests, things are different. If you find yourself duplicating lots of code, it indicates that your unit tests contain too much logic. Thus, they should be shortened.

For example:

@Test
public void ensureCatHungryByDefault()
{
    var cat = new Cat();
    assertTrue(cat.Hungry);
}

@Test
public void ensureCatFed()
{
    var cat = new Cat();
    var food = new Whiskas(100.Gramm);
    cat.feed(food);
    assertFalse(cat.Hungry);
}

@Test
public void ensureCatThrowsOnNull()
{
    var cat = new Cat();
    exception.expect(IllegalArgumentException.class);
    cat.Feed(null);
}
```

<p>and:</p>

<pre class="lang-java prettyprint-override"><code>@Test
public void ensureDogHungryByDefault()
{
    var dog = new Dog();
    assertTrue(dog.Hungry);
}

@Test
public void ensureDogFed()
{
    var dog = new Dog();
    var food = new Pedigree(600.Gramm);
    dog.feed(food);
    assertFalse(dog.Hungry);
}

@Test
public void ensureDogThrowsOnNull()
{
    var dog = new Dog();
    exception.expect(IllegalArgumentException.class);
    dog.Feed(null);
}
</code>```

contain some duplication, but it's acceptable. The two flaws of duplication are the duplication of logic and duplication of data. There is no business logic inside unit tests. As for the data, the data related to a dog is different from the data related to a cat, thus we consider that there is no duplication.

By keeping cat and dog tests separate, you gain both readability and flexibility:

You gain readability, because if you later break code, you can easily understand that the change broke only Cat, only Dog or both.

You gain flexibility, because you can work on changing Cat class and deal with the corresponding unit tests, without having to deal with other pets. If tests were common to all pets, it could have created a difficulty when your business logic changes, such as all cats mutate, and should be fed very differently from now.

¹ A slug is a transformation of text which consists of removing all diacritics and replacing all consecutive special characters or whitespace by dashes. Example: Il était une fois un... hérisson gives il-etait-une-fois-un-herrison. This technique is usually used in URIs, and can also be used for search purposes where searching for herisson should also include hérisson in search results.

Title: DRY code, DRY tests?

Body:
You're right when you tell that you may use the first approach before refactoring. While personally, I disagree with this approach, that's the rule of three from Refactoring by Martin Fowler (page 58):

Here's a guideline Don Roberts gave me: The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor.

It remains that the duplication in code is annoying. From here, you have to think about the exact context of the duplication:

Either two classes are related (for example both Cat and Dog can be fed, and it takes the same steps to feed them both, except the food which will change), in which case, create an inheritance (in my example, a parent class Pet),

Or two classes are unrelated, and just rely on the same method. For example, WebRequest class may rely on GetSlug¹ to find the slug of the current request; Customer may also rely on GetSlug to normalize the name of the customer for further search purposes. However, WebRequest and Customer are totally unrelated, and it makes no sense to create a common object for those classes.

Here, the solution would be to call a common method from those two classes, by instantiating the third class containing this method. For example, both RequestUri and CustomerName may become objects implementing ISlug interface.

In unit tests, things are different. If you find yourself duplicating lots of code, it indicates that your unit tests contain too much logic. Thus, they should be shortened.

For example:

@Test
public void ensureCatHungryByDefault()
{
    var cat = new Cat();
    assertTrue(cat.Hungry);
}

@Test
public void ensureCatFed()
{
    var cat = new Cat();
    var food = new Whiskas(100.Gramm);
    cat.feed(food);
    assertFalse(cat.Hungry);
}

@Test
public void ensureCatThrowsOnNull()
{
    var cat = new Cat();
    exception.expect(IllegalArgumentException.class);
    cat.Feed(null);
}

and:

@Test
public void ensureDogHungryByDefault()
{
    var dog = new Dog();
    assertTrue(dog.Hungry);
}

@Test
public void ensureDogFed()
{
    var dog = new Dog();
    var food = new Pedigree(600.Gramm);
    dog.feed(food);
    assertFalse(dog.Hungry);
}

@Test
public void ensureDogThrowsOnNull()
{
    var dog = new Dog();
    exception.expect(IllegalArgumentException.class);
    dog.Feed(null);
}

contain some duplication, but it's acceptable. The two flaws of duplication are the duplication of logic and duplication of data. There is no business logic inside unit tests. As for the data, the data related to a dog is different from the data related to a cat, thus we consider that there is no duplication.

By keeping cat and dog tests separate, you gain both readability and flexibility:

You gain readability, because if you later break code, you can easily understand that the change broke only Cat, only Dog or both.

You gain flexibility, because you can work on changing Cat class and deal with the corresponding unit tests, without having to deal with other pets. If tests were common to all pets, it could have created a difficulty when your business logic changes, such as all cats mutate, and should be fed very differently from now.

¹ A slug is a transformation of text which consists of removing all diacritics and replacing all consecutive special characters or whitespace by dashes. Example: Il était une fois un... hérisson gives il-etait-une-fois-un-herrison. This technique is usually used in URIs, and can also be used for search purposes where searching for herisson should also include hérisson in search results.


答:
I generally write enough tests to give me confidence that my implementation is correct, but no more than that. How many tests this is depends on the problem at hand.

If you're feeling very unsure about the correct implementation of the behaviour, you'll probably end up writing a full set of tests for each endpoint and refactoring at the end: going from Approach 1 to Approach 2, as you've labelled them. Kent Beck calls this sort of programming "driving in a low gear".

If your problem is not so complex, you might want to change up a gear or two. Remember, TDD is about doing "the simplest possible thing" at every step. If you can see that the simplest way to make your next test pass is just to call the method you've already implemented, then you can go home early.

If you get an unexpected bug or test failure, you're free to slow down, write more tests, and drive in a lower gear again. TDD often feels like this: constantly adjusting your pace to match your confidence and fear levels. It's one of the themes of Kent Beck's book.

Remember, you're not aiming for 100% coverage of every public method; just enough to give you confidence that your code is correct.

Title: DRY code, DRY tests?

Body:
At some point I had to create some class "Class1" and that class needs a method "method". So I have the following:

```<code>Class1MethodTest: A total of N tests that check the behavior of Class1.method
Class1 method: A full implementation of the method
</code>```

But a bit later I need a different class "Class2" to have a completely similar method "method". Now I have several approaches:

Approach 1

```<code>Class1MethodTest: A total of N tests
Class1 method: Full implementation
Class2MethodTest: Another set of identical tests
Class2 method: Another full implementation
</code>```

Pros: Stupid simple

Cons: not DRY

At least that's the first attempt and I might even write this before doing any refactoring, right?

Approach 2:

```<code>_hidden_private_implementation_function: Full implementation of required method
Class1MethodTest: A total of N tests
Class1 method: Call hidden_private_whatever
Class2MethodTest: Another set of identical tests
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY code, still stupid simple

Cons: Tests aren't DRY, "Test interface, not implementation"

Approach 3:

```<code>MethodTest: A total of N tests
TotallyPublicCommonMethod: Full implementation of required method
Class1MethodTest: Just one test to verify that Class1 method calls the Public one
Class1 method: Call public common method
Class2MethodTest: One more test
Class2 method: Also call common method
</code>```

Pros: DRY, stupid simple

Cons: .. any other than "You're testing implementation, not interface"?

Approach 4:

This is where it gets a bit exotic. Python allows me to DRY the "Approach 3" directly:

```<code>_hidden_private_implementation_function: Full implementation of required method
makeTestForClass(cls): return a total of N tests for class cls
Class1MethodTest = makeTestForClass(Class1)
Class1 method: Call hidden_private_whatever
Class2MethodTest = makeTestForClass(Class2)
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY, "Don't test implementation"

Cons: Not that simple. Too hard to modify if I ever decide to change something in Class1.method, but not Class2.method

I can think of a couple more approaches but those are not very different from these above.

Right now I have some code looking something like "Approach 1" and I am thinking on which way I should go next to make it all cleaner and better.


问:
How to plan for multi-platform application development
In my earlier days of programming, I was using Visual Basic for learning. It taught me many concepts, and I was able to make some cool programs (in my opinion, anyways...). I have expanded my horizon to basic C/C++, PHP, and MySQL.

One of my most favourite projects, I want to turn into a multi-platfrom (for x86/x64) windowed application, and have it open source. I decided on the license already, but I want to know, before I start developing in a new language, how can I choose which language to use, that is multi-platform, and allows for windows to be created? I do not wish to use web technologies, as the application will work with lots of local files at a time.

This is not a question about which technology is better, but about which one would be useful for this project. I know something has to be possible, because there are apps that run as Mac OSX binaries, Windows binaries, and even Linux binaries, all in windows (i.e. VLC Media Player, Firefox (Ice Wheazel), etc)

答:
Each OS uses its own file formats for executable files and shared libraries and each OS also has its own API for applications to interact with it. This means that generally, binaries built for OS A can not be used on OS B.

There are two ways to write applications that can be used on multiple platforms:

You use a virtual machine (VM) that hides all/most of the differences between the OSes. Web technologies are based on this (with the browser providing the VM), but also a languages like Java and interpreted languages.

You build separate binaries for each OS that you support and you use cross-platform libraries to hide most of the differences between the OSes from your main application logic.

When choosing a language for multi-platform development, the main considerations are

What platforms do I want to support

What languages am I comfortable in using

For which of those languages are there VMs or compilers targeting all of the required platforms

Do those languages support the features I want (e.g. a GUI), possibly through libraries

For natively compiled languages, for which do there exist cross-platform libraries that support all required platforms or am I prepared to write one myself.


问:
How can I create a set of random numbers based on a total and number of objects?
For example with:

Total population = 400000

Number of villages = 800

The average population is 500

How can I randomize the amount of people in each village using a specified deviation (eg +-50) so that it equals the total population?

I came up with a solution using this normal distribution class

Basically I created a normal distribution and used the Probability Density Function to determine the amount of villages at each discrete level (until the population total was hit).

This is something I wrote quickly to demonstrate:

```<code> NormalDist dist = new NormalDist(500.0, 50.0);
 int popX = 500;
 int numberOfPopXVillages = Convert.ToInt32(Math.Floor(dist.PDF(popX) * 800)); ;
 int totalSum = 0;
 do
 {
     Console.WriteLine(numberOfPopXVillages);
     totalSum += popX * numberOfPopXVillages;
     totalSum += (1000 - popX) * numberOfPopXVillages;
     ++popX;
     numberOfPopXVillages = Convert.ToInt32(Math.Floor(dist.PDF(popX) * 800));
 } while (numberOfPopXVillages >= 5);
 Console.WriteLine(totalSum);
</code>```

The total sum here is 400000. The algorithm isn't perfect but I'll keep working on it. Thanks everyone.

答:
First, you use Normal distribution to generate population of each village. This should give you number that is pretty close to total population. To get exact population, just add or remove the difference evenly across all villages.

The problem of this algorithm is that there is some probability of generating negative population. But that heavily depends on parameters. For parameters from your example, the probability is extremely slim. But for parameters (10000, 100, 50), the probability is there.

```<code>import random

def generate_villages(total, count, deviation):
    average = total / count
    villages = [random.gauss(average, deviation) for _ in range(count)]
    diff = (sum(villages) - total)/count
    villages = [round(v - diff) for v in villages]
    return villages

vil = generate_villages(400000, 800, 50)
print(vil)
print(sum(vil))
</code>```

While this code doesn't give precise number. It deviates +-10 which is fine.

Body:
First, you use Normal distribution to generate population of each village. This should give you number that is pretty close to total population. To get exact population, just add or remove the difference evenly across all villages.

The problem of this algorithm is that there is some probability of generating negative population. But that heavily depends on parameters. For parameters from your example, the probability is extremely slim. But for parameters (10000, 100, 50), the probability is there.

import random

def generate_villages(total, count, deviation):
    average = total / count
    villages = [random.gauss(average, deviation) for _ in range(count)]
    diff = (sum(villages) - total)/count
    villages = [round(v - diff) for v in villages]
    return villages

vil = generate_villages(400000, 800, 50)
print(vil)
print(sum(vil))

While this code doesn't give precise number. It deviates +-10 which is fine.