问:
Trying to get a better understanding of object-oriented design's performance pitfalls
I'm currently in a high-performance computing class taught in C++. Usually, I do work in C#, meaning everything is taken care of for me, and optimization comes behind maintainability and higher-level features. It's like... a nice productivity furnace that keeps me nice and warm in the programming project winter at the expense of my CPU cycle/cache miss electricity bill. However, now that I'm in C++ and efficient algorithm land, that stuff takes a back seat to optimization.

Since most of my work has been in C#, object-oriented programming is sort of my style. However, I have been reading/hearing more and more about how object-oriented code is an enemy of performance. As my understanding of software architecture shifts from being exclusively about class structure and encapsulation to understanding how things are disposed of from L1 cache and pipelining, I'm trying to understand the real reasons why object-oriented design (especially as it applies to C++) causes waste of hardware resources. Can you guys give me a few basic reasons why it impacts computer performance? I know there are other debates about OOP, but I'd like to just keep it to performance on a hardware and algorithmic level.

答:
As was already discussed, virtual functions can hurt performance. Not so much because of the v-table lookup which is extremely fast, but more because of the lost opportunity to inline, which saves function calling overhead and allows the compiler to optimize across function boundaries. Note though, in c++11 the 'final' keyword should allow inline of virtuals. Furthermore, this is only an issue with polymorphism. You don't always use polymorphism when you use OOD.

One of the biggest things in performance nowadays is cache misses. The difference in speed between CPU and RAM has grown a lot over the last decades. A cache miss can cause the CPU to just wait for upwards of 200 cycles, while you grab data. Trying to minimize this is a complicated topic, but one thing that's generally a good idea is this: if you have a tight loop in the critical path, you would ideally like the data being accessed to be stored exactly sequentially with no gaps. The CPU is actually quite smart, and will notice you are retrieving data sequentially. This means it will actually prefetch data and prevent you from cache missing, even on data that's never been requested yet!

OOD however pushes you towards a certain memory layout. For instance, suppose you have an object of class A, with members x, y, and z. These are all important. But the critical path of your program consists of performing some operation on an enormous array of A's, just on members x and y. Those z's are potentially hurting your performance, because they are useless gaps in the storage. If z is a very large type this could increase branch misses substantially.

Note that if you do use polymorphism, the above example becomes much more horrible: instead of an array of A's by value, you would have an array of pointers to A. Now your data is all over the place, which sucks.

It is still possible in many places to use OOD patterns but in a way that is conscious of these issues. For instance, one pattern I've used several times is generating "Op" objects. If you have a very defined critical path, then any code before or after this critical path is basically free. If your A contains lots of important information e.g. for configuration or setup purposes, it may be nice to create a leaner object with only necessary, properly arranged data for the loop in the critical path. I often call this class A_Op or similar, and give A a method that emits its "Op" class.

Edit: I would be remiss not to briefly mention templates here. Templates let you perform similar abstractions to OOD, but with zero run-time cost. A well known example is compile-time polymorphism (not true polymorphism in some sense) via curiously recurring template pattern. Or policy based design.


问:
Why are packed structures not part of the C language?
Every C compiler offers the option to "pack" C structures (e.g. __attribute__ ((__packed__)), or #pragma pack()). Now, we all know that packing is required, if we'd like to send or store data in a reliable way. This must also have been a requirement since the first days of the C language.

So I wonder why packed structures are not part of the C language specification? They're not even in C99 or C11 even though the necessity of having them is known for decades now? What I am missing? Why is it compiler specific?

答:
It is compiler-specific because it is not in the standard. And it's not in the standard because it would be difficult to specify in a way that wouldn't require lots of implementation effort for compilers of obscure platforms with enforced alignment restrictions.

And none of that effort has much justification, because every compiler/platform that anyone using a C89 or later compiler cares about already has it implemented.

ContentLicense: CC BY-SA 3.0


问:
Using a binary from a project that violates GPL
There is an open source project which uses GPLv2. It had numerous releases that complied with GPL in the past where source code was available for given binaries. The newest source code is about 18 months old and is being called a last "official release".

Since that OSed "last version" further development has been done by a single main developer. Features have been added and it is clearly visible that the code must have been changed. The main developer only holds part of the copyright for the whole package (it is not 100% his work, the project was started as a fork of another GPLed project). Lets call the ongoing development a TRUNK branch.

The problem is that the latest development is done as closed source and only binaries are being distributed for the TRUNK branch and no source code was revealed yet. While this most likely is a GPL violation and is a bad thing itself, I dont mind this (even as I should) because I want to use the TRUNK binaries.

My question is - what is the legal status of such TRUNK binaries that have no source available to them? Are these poised somehow? I want to use the binaries in my project which is open source itself but the binaries would be used in a standalone working unit that only is used for data acquisition so I most likely wont need to modify the unavailable TRUNK source code anyway.

答:
The legal status for GPL binaries for which no corresponding sources are available is that they may not be distributed.

As a user of a GPL application, you are not required to actually have a copy of the sources. If you obtained a binary that violates the GPL, you are not automatically in violation of the GPL yourself, that only happens if you redistribute the binary yourself.


问:
Why are these seemingly unnecessary merges happening in git?
Consider this screenshot from our development repository:

We are relatively new to git, so things are still somewhat confusing. The question at hand: If you take a look at the commits by me at the very top; are confusing to us. Why do I need to merge something if I didn't even branch anything?

I commited the adjust buildpath commit, and after that, git immediately made me do a merge. but with what? The invitation branch is not interesting for me, and I never touched it in any way.

Where did this anonymous blue branch come from and why? My colleague (blue avatar) only works in the invitation branch currently.

Can someone explain to me why this is happening in git-layman terms (as I said, we are new to this)?

答: Short answer in git layman terms: your teal colleague is mistaken if they think they were only working on the 'invitation' branch. They were committing + pushing to master, and only then merging back to invitation.</p>


问:
Are first-class functions a substitute for the Strategy pattern?
The Strategy design pattern is often regarded as a substitute for first-class functions in languages that lack them.

So for example say you wanted to pass functionality into an object. In Java you'd have to pass in the object another object which encapsulates the desired behavior. In a language such as Ruby, you'd just pass the functionality itself in the form of an anonymous function.

However I was thinking about it and decided that maybe Strategy offers more than a plain anonymous function does.

This is because an object can hold state that exists independently of the period when it's method runs. However an anonymous function by itself can only hold state that ceases to exist the moment the function finishes execution.

In an object-oriented language that supports first-class functions, does the strategy pattern have any advantage over using functions?

答:
It is not true that an anonymous function can only hold state that ceases to exist when the function finishes execution.

Take the following example in Common Lisp:

```<code>(defun number-strings (ss)
  (let ((counter 0))
    (mapcar #'(lambda (s) (format nil "~a: ~a" (incf counter) s)) ss)))
</code>```

This function takes a list of strings and prepends a counter to each element of the list. So, for example, invoking

```<code>(number-strings '("a" "b" "c"))
</code>```

gives

```<code>("1: a" "2: b" "3: c")
</code>```

The function number-strings internally uses an anonymous function with a variable counter that holds state (the current value of the counter) which is reused every time the function is invoked.

In general, you can think of a closure as an object with only one method. Alternatively, an object is a collection of closures that share the same closed-over variables. So I am not sure whether there are cases in which you need to use an object instead of a closure: I would argue that both are ways of looking at the same pattern from different perspectives.

In particular, the strategy pattern requires an object with only one method, so a closure should do the job. But, as Philipp has observed in his answer, depending on the circumstances (complex state) and programming languages you may get a more elegant solution by using objects.

Body:
It is not true that an anonymous function can only hold state that ceases to exist when the function finishes execution.

Take the following example in Common Lisp:

(defun number-strings (ss)
  (let ((counter 0))
    (mapcar #'(lambda (s) (format nil "~a: ~a" (incf counter) s)) ss)))

This function takes a list of strings and prepends a counter to each element of the list. So, for example, invoking

(number-strings '("a" "b" "c"))

gives

("1: a" "2: b" "3: c")

The function number-strings internally uses an anonymous function with a variable counter that holds state (the current value of the counter) which is reused every time the function is invoked.

In general, you can think of a closure as an object with only one method. Alternatively, an object is a collection of closures that share the same closed-over variables. So I am not sure whether there are cases in which you need to use an object instead of a closure: I would argue that both are ways of looking at the same pattern from different perspectives.

In particular, the strategy pattern requires an object with only one method, so a closure should do the job. But, as Philipp has observed in his answer, depending on the circumstances (complex state) and programming languages you may get a more elegant solution by using objects.


答:
There are three main factors.

Some processors cannot access unaligned data (for example an integer or float starting on an odd address). Attempting to do triggers an exception.

Some processors can access unaligned data, but at a performance cost.

Most structures are accessed by a single set of C/C++ source code, and interoperability with other languages is the exception, not the rule.

With these factors in mind, both the standard and all C/C++ compilers routinely pad structures to ensure optimal alignment for the processor, but also provide mechanisms to override this if needed for the purposes of interop.

This is by no means something that has been overlooked. It is extremely well understood and the current situation is by design. The latest versions of the C++ standard have extensive support for handling alignment issues, which perhaps you are not familiar with.

Title: Why are packed structures not part of the C language?

Body:
Every C compiler offers the option to "pack" C structures (e.g. __attribute__ ((__packed__)), or #pragma pack()). Now, we all know that packing is required, if we'd like to send or store data in a reliable way. This must also have been a requirement since the first days of the C language.

So I wonder why packed structures are not part of the C language specification? They're not even in C99 or C11 even though the necessity of having them is known for decades now? What I am missing? Why is it compiler specific?


答:
When the language supports references to function (Java does since version 8), these are often a good alternative for strategies, because they usually express the same thing with less syntax. However, there are some cases where a real object can be useful.

A Strategy interface can have multiple methods. Let's take an interface RouteFindingStragegy as example, which encapsulates different route finding algorithms. It could declare methods like

Route findShortestRoute(Node start, Node destination)

boolean doesRouteExist(Node start, Node destination)

Route[] findAllPossibleRoutes(Node start, Node destination)

Route findShortestRouteToClosestDestination(Node start, Node[] destinations)

Route findTravelingSalesmanRoute(Node[] stations)

which then would all be implemented by the strategy. Some route-finding algorithms might allow internal optimizations for some of these use-cases and some might not, so the implementor can decide how to implement each of these methods.

Another case is when the strategy has an inner state. Sure, in some languages closures can have inner state, but when this inner state gets very complex, it often becomes more elegant to promote the closure to a full-fledged class.

Title: Are first-class functions a substitute for the Strategy pattern?

Body:
The Strategy design pattern is often regarded as a substitute for first-class functions in languages that lack them.

So for example say you wanted to pass functionality into an object. In Java you'd have to pass in the object another object which encapsulates the desired behavior. In a language such as Ruby, you'd just pass the functionality itself in the form of an anonymous function.

However I was thinking about it and decided that maybe Strategy offers more than a plain anonymous function does.

This is because an object can hold state that exists independently of the period when it's method runs. However an anonymous function by itself can only hold state that ceases to exist the moment the function finishes execution.

In an object-oriented language that supports first-class functions, does the strategy pattern have any advantage over using functions?


问:
How is the system software stored in Computer?
We usually have a lot of system software inside our PC's like Operating Systems (which contains different interrupt handlers etc.), Assemblers and Compilers, Drivers. My question is how do we store this information in the computer? Are these all softwares stored in machine instruction format inside the computer at specific locations inside the PC-ROM? Or they are stored as is in the high-level language (like C) in which they are written and then compiled every time the programs are called?</p>

答:
The processors of computers can only understand instructions of their specific machine language. So as you guessed, most of the programs (including the operating system itself) are stored in machine language format on a hard disk or other storage device, or in the permanent EPROM memory of the computer. When it is required, the program code is loaded into memory and then it can be executed.

There are some programs (usually called "scripts") though which are stored in source code format on the disk and then interpreted by a suitable compiler when there is a need to run them. However, the code of the compiler itself must be directly executable by the system, so it must be in machine code.

There exists a cross between these two options as well, called bytecode. In this case, the compiler transforms the original, human-readable source code into a shorter and lower level binary format which is not human readable anymore, but not directly interpretable to a physical processor either. So this requires another compiler or interpreter in a special environment to execute it on a physical device. This special environment is called a virtual machine. This is how Java or C# works, for example.

The advantage of this compared to compiling directly to machine code is that the machine code is specific to a processor family, so it can only run on computers with the right kind of processors in them. Whereas the bytecode can be independent of any specific processor architecture or machine language format, so it is runnable on many different kinds of computers, using the virtual machine variant specific to that type of computer.

And the advantage over interpreted scripts is that the bytecode is much more concise and standardized, so compiling it further to machine code is simpler and much faster than interpreting scripts. Moreover, the bytecode compiler can already verify the code's correctness to a significant extent way before deploying it to a physical machine to run it.

If you want to understand better how computers are built from the ground up, I recommend the book CODE by Charles Petzold.


问:
Uniform identifier/class naming across HTML, CSS and JS
How does one ensure that HTML, CSS and JS have uniform identifiers. For example, one such set of identifiers could be class names. e.g.:

CSS:

```<code>.user-profile{
  ...
}
</code>```

JS:

```<code>document.getElementsByClassName( "user-profile" ).(...)
</code>```

HTML:

```<code><div class="user-profile"> ... </div>
</code>```

Are there any IDEs that can provide this functionality? Given that these are technically strings, I'd assume it would be hard to determine 'equality'.

答:
There are no variables in HTML. I think you are talking about id and class attributes.

When you change an id or a class, the easiest way to reflect the change in CSS and JavaScript is to grep the related files.

I'm not sure an automated renaming by an IDE would be helpful: there are many cases where you don't want CSS/JavaScript files to be modified. A basic example: you change a class of an element, because you want a different style.

Also, if you have to do a lot of changes in ids and classes, check that you're using proper naming conventions and you chose the values thoughtfully from the beginning.


问:
Should I place functions that are only used in one other function, within that function?
Specifically, I'm writing in JavaScript.

Let's say my primary function is Function A. If Function A makes several calls to Function B, but Function B is not used anywhere else, then should I just place Function B within Function A?

Is that good practice? Or should I still put Function B at the same scope as Function A?

答:
Defining function B within function A gives function B access to A's internal variables.

So, a function B defined within a function A gives the impression (or at least the possiblity) that B is using or altering A's local variables.  While defining B outside of A makes it clear that B doesn't.

Therefore, for the clarity of the code, I would define B within A only if B needs to access local variables of A.  If B has a clear purpose that is independent of A, I would definitely define it outside of A.


问:
Adding field to the class at runtime - design pattern
Imagine your customer want's to have a possibility to add new property (e.g. color) to product in their eshop in their CMS.

Instead of having properties as fields:

```<code>class Car extends Product {
   protected String type;
   protected int seats;
}
</code>```

You would probably end up doing something like:

```<code>class Product {
   protected String productName;
   protected Map<String, Property> properties;
}

class Property {
   protected String name;
   protected String value;
}
</code>```

That is, creating own type system on top of existing one. It feels to me like this could be seen as creating domain specific langauge, or couldn't?

Is this approach a known design pattern? Would you solve the problem differently? I know there are languages where I can add a field in runtime, but what about database? Would you rather add/alter columns or used someting as shown above?

Thank you for your time :).

答:
Congratulations! You have just circumnavigated the programming language / type system globe, arriving on the other side of the world from whence you departed. You have just landed on the border of dynamic language / prototype-based object land!

Many dynamic languages (e.g. JavaScript, PHP, Python) allow one to extend or change object properties at runtime.

The extreme form of this is a prototype based language like Self or JavaScript. They
do not have classes, strictly speaking. You can do things that look like class-based, object-oriented programming with inheritance, but the rules are greatly relaxed compared to more sharply-defined, class-based languages like Java and C#.

Langauges like PHP and Python live in the middle ground. They have regular, idiomatic class-based systems. But object attributes can be added, changed, or deleted at runtime--albeit with some restrictions (like "except for built-in types") that you don't find in JavaScript.

The big tradeoff for this dynamism is performance. Forget how strongly or weakly typed the language is, or how well it can be compiled down to machine code. Dynamic objects must be represented as flexible maps/dictionaries, rather than simple structs. This adds overhead to every object access. Some programs go to great lengths to reduce this overhead (e.g. with phantom kwarg assignment and slot-based classes in Python), but the extra overhead is usually just par for the course and the price of admission.

Getting back to your design, you're grafting the ability to have dynamic properties onto a subset of your classes. A Product can have variable attributes; presumably an Invoice or an Order would and could not. It's not a bad way to go. It gives you the flexibility to have variation where you need it, while remaining in a strict, disciplined language and type system. On the down side, you are responsible for managing those flexible properties, and you'll probably have to do so through mechanisms that look slightly different from more native attributes. p.prop('tensile_strength') rather than p.tensile_strength, for instance, and p.set_prop('tensile_strength', 104.4) rather than p.tensile_strength = 104.4. But I've worked with and built many programs in Pascal, Ada, C, Java and even dynamic languages that used exactly such getter-setter access for non-standard attribute types; the approach is clearly workable.

By the by, this tension between static types and a highly varied world is extremely common. An analogous problem is often seen when designing database schema, especially for relational and pre-relational data stores. Sometimes it's dealt with by creating "super-rows" that contain enough flexibility to contain or define the union of all imagined variations, then stuffing any data that comes along into those fields. The WordPress wp_posts table, for example, has fields like comment_count, ping_status, post_parent and post_date_gmt that are only interesting under some circumstances, and that in practice often go blank. Another approach is a very spare, normalized table like wp_options, much like your Property class. While it requires more explicit management, items in it are rarely blank. Object-oriented and document databases (e.g. MongoDB) often have an easier time dealing with changing options, because they can create and set attributes pretty much at will.


问:
Where to save something between invocations?
The 2nd time I run this program I'd like it to start in the same HDD location as the previous instance. How should I save, or remember, where I was so the program starts in the same place?

I'd like to persist my previous location the same way across MAC, Linux, Windows, ...

Where is a good place to save my location so it's available to me the next time I run?

答:
The best place to store those things is in a file below the users home directory.

I'd like to persist my previous location the same way across MAC, Linux, Windows

The conventions how to find the users home directory are different at different operating systems, also the conventions how programs have to use the folder hierarchy below there. At least, there is always an environment variable available which can be checked for getting the home directory root (%UserProfile% for Windows, $HOME for Linux/Unix/Mac). See  http://en.wikipedia.org/wiki/Home_directory for a list.

This former SO post tells you how to determine the home directory when using Python in a platform-independend way.

For Windows, here is some more detailed information where exactly to store application files:

Link

For Unix/Linux, look into the filesystem hierarchy standard:

http://www.pathname.com/fhs/pub/fhs-2.3.html#HOMEUSERHOMEDIRECTORIES

ContentLicense: CC BY-SA 4.0


问:
How to layer if statements when order of logic is irrelevant?
Basically I have a series of logic in my website that can lead to 5 total outcomes. Basically two different if tests and then a catch all else statement.

For example:

```<code>if cond1:
    if mod1:
        #do things
    elif mod2:
        #do things
elif cond2:
    if mod1:
        #do things
    elif mod2
        #do things
else:
    #do things
</code>```

I was thinking about rewriting it like this:

```<code>if cond1 and mod1:
    #do things
elif cond1 and mod2:
    #do things
elif cond2 and mod1:
    #do things
elif cond2 and mod2:
    #do things
else:
    #do things
</code>```

Is there any real difference in these two coding options/a better choice for this kind of logic testing?

答:
Nested if statements (or nested anything) adds complexity to the code. It makes it harder for someone to read and understand the code. There is actually a complexity measurement called Cyclomatic complexity. The way it works is each time there is a conditional branch it adds one point. Higher points means more complex. There are some automated tools that can scan your code and score it for you. </p>

<p>One of our primary jobs as Developers is to decrease the complexity as much as possible. I try to avoid nested blocks when possible so your second choice looks like a good way. </p>

Body:
Nested if statements (or nested anything) adds complexity to the code. It makes it harder for someone to read and understand the code. There is actually a complexity measurement called Cyclomatic complexity. The way it works is each time there is a conditional branch it adds one point. Higher points means more complex. There are some automated tools that can scan your code and score it for you.

One of our primary jobs as Developers is to decrease the complexity as much as possible. I try to avoid nested blocks when possible so your second choice looks like a good way.


问:
How to convert this recursive problem to iterative? Line Simplification algorithm fails to run due to Maximum Recursion Depth being hit
I am implementing the Douglas, Peucker's Line Simplification algorithm in Python. I started with this implementation. However, it fails to run in Python due to Maximum Recursion Depth being hit. How can I convert this algorithm to a iterative one? I am not able to imagine this problem in an iterative view.

My expectation is to get approach/hint which can be used rather than actual code. Is it possible to use some internal stack to resolve the stack overflow (or avoid the maximum recursion depth)?

Update:
Found the iterative implementation of the algorithm here.

答:
I would use a stack, but just keep it as simple as possible. After all, all you need to know what to do next is a pair of numbers.

```<code>def line_simple(array, epsilon):
    keep = [False for i in array]
    keep[0], keep[-1] = True, True
    stack = deque()
    stack.append((0, len(array) -1))

    while len(stack) != 0:
        left, right = stack.pop();
        worst_distance, worst_index = find_worst(array, left, right)

        if worst_distance > epsilon:
            keep[worst_index] = True
            stack.append((left, worst_index))
            stack.append((worst_index, right))

    return keep
</code>```

All you have to do is write find_worst. Note that find_worst should take arguments as I've shown; you should not do find_worst(array[left:right]) which makes a copy of the array. Make sure that find_worst returns 0 if right-left = 0 or 1.

Body:
I would use a stack, but just keep it as simple as possible. After all, all you need to know what to do next is a pair of numbers.

def line_simple(array, epsilon):
    keep = [False for i in array]
    keep[0], keep[-1] = True, True
    stack = deque()
    stack.append((0, len(array) -1))

    while len(stack) != 0:
        left, right = stack.pop();
        worst_distance, worst_index = find_worst(array, left, right)

        if worst_distance > epsilon:
            keep[worst_index] = True
            stack.append((left, worst_index))
            stack.append((worst_index, right))

    return keep

All you have to do is write find_worst. Note that find_worst should take arguments as I've shown; you should not do find_worst(array[left:right]) which makes a copy of the array. Make sure that find_worst returns 0 if right-left = 0 or 1.


问:
How do we add software to a machine?
When we build a new machine, how do we add software to that machine?

I know we have assemblers and compilers that convert the high-level code into machine code for it to understand. But having designed a new machine with some new architecture, how do we proceed ahead and add assembler and compilers to a machine understanding only machine language?

As far as I know, we do not write the assemblers or compilers in machine language, so how do we add these programs to the new machine so that it can run programs in high-level language?

答:
We first build assemblers and compilers for them, compile those for existing computers (the result are "cross-", as they are executing on an host which hasn't the target architecture).  Those are usually build before any machine having that architecture (and used with simulators to design the chips).

When you have that, it exactly the same way than for a computer which is using an old architecture.  Write a loader which is able to load a file from somewhere (HD, USB, network) put that at a fixed place and then execute it and put the loader in a ROM at the address which is executed at startup by your processor.

Title: How do we add software to a machine?


问:
Can't understand on how to implement MVP/MVC for my software requirements
Recently I decided to start developing a client/service based system using WCF and a Duplex Channel (callbacks from Service to client). The clients will behave as "slaves", that is, they will only connect to server and from then on, only the server communicates with them. Eventually the server may request that the clients send "data streams" to him (frequent updates of new content/objects).

I want to make my software as loosely coupled as possible, but even reading about the different patterns for this, such as MVC and MVP, they don't seem to be designed to fulfill my specific requirements.

What is the best code architecture or pattern for my problem? Considering the technologies I am using?

答:
Patterns Abstract Details, not Vice Versa

The clients will behave as "slaves", that is, they will only connect to server and from then on, only the server communicates with them. Eventually the server may request that the clients send "data streams ... MVC and MVP, ... don't seem to be designed to fulfill my specific requirements."

I'm getting the feeling that you are trying to find a pattern that maps directly to your hardware/network setup. This is the antithesis of Object Oriented design patterns.

Software Systems are Organic Molecules of Patterns

As in chains of patterns. The high-level parts of M.V.P. are in turn their own complex Object Oriented structures as needed to represent nested abstract layers eventually getting to the servers. You're missing all the design between the top layer MVC concept and the server - server communication.

Prototyping

Perhaps you should take a prototype mindset. As Fred Brooks said in the Mythical Man Month

“The management question, therefore, is not whether to build a pilot system and throw it away. You will do that. The only question is whether to plan in advance to build a throwaway, or to promise to deliver the throwaway to customers.”

I'm not suggesting you build an entire system; just enough to experiment with the architecture variations. You really need to understand where you're going with this before you commit to delivery schedules.

As far as Ive been able tell MVP vs MVC is a matter of emphasis. MVP has a more intimate association between the V-and-C.

Following is a quote from MVP: Model-View-Presenter
The Taligent Programming Model for C++ and Java

...normalize the separation between the Model and the View-Controller, which we refer to as a Presentation. This represents the breaking down of a programming problem into two fundamental concepts: Data Management and User Interface.

I think it boils down to how one wants to model things. If MVC works in a given case does not mean MVP is wrong for that case.

Software design patterns are guidelines, not hard and fast literal rules to be followed to the exclusion of good design throughout your system.

MVC (MVP) and WCF Systhesis

MVC/P has become the go-to design paradigm for GUI applications so I would not get sidetracked because WCF based on Service Oriented Architecture (SOA).

As far as I can tell one can easily use the WCF .net framework within the Model-View-Whatever pattern.


问:
Which Continuous Integration framework do you use and why?
There are quite a few different Continuous Integration (CI) frameworks out there and I'm wondering which is the most popular.  Which frameworks have you used at firms where you work?

Is there any reason one CI framework is more popular than another - perhaps this is to do with the features it offers, things that integrate into it or maybe its just marketing?

It seems like continuous integration is used more in the Java and .net worlds than say ruby or python.  Why is this?

答: Pulse. It basically Just Works, which for a busy build engineer is a big deal. They also have really excellent technical support. The main reason I love it so much is that we have 250+ projects and it handles them without a hiccup; I cannot say the same for Hudson.</p>

ContentLicense: CC BY-SA 2.5


问:
In C++, are acquire-release memory order semantics transitive?
According to cppreference, we can use release-acquire semantics to ensure write-read precedence between two threads as follows:

```<code>// Thread A
1. Write to X
2. Atomic store to Y with std::memory_order_release
// Thread B
3. Atomic load at Y with std::memory_order_acquire
4. Read at X
</code>```

Supposing that 2 is ordered before 3 (take it as a given that this occurs according to Y), we are guaranteed that A's write to X is visible to B since we can establish a total order on the events (as conveniently described by my enumeration above) because 1 sequenced-before 2 synchronizes-with 3 sequenced-before 4 and because release-acquire ensure that all of A's writes are visible to B after 3.

However, the link above explicitly states that in this situation "all memory writes (non-atomic and relaxed atomic) [by A become] visible side-effects in thread B." My question is then: are "visible side-effects" considered writes made B to threads previously unaware of A's writes?

In other words, suppose I had a third thread C and another atomic:

```<code>// Thread A
1. Write to X
2. Atomic store to Y with std::memory_order_release
// Thread B
3. Atomic load at Y with std::memory_order_acquire
4. Read at X
5. Atomic store to Z with std::memory_order_release
// Thread C
6. Atomic load at Z with std::memory_order_acquire
7. Read at X
</code>```

(Assume similarly that 5 happens-before 6). Would C read A's write to X? Or is B's "visible side-effect" on X not considered a write?

答:
Formally, you are asking if the side effect on X in thread A is visible with respect to value computation of X in thread C.

For that to be true, 1 needs to happen-before 7.

A happens-before B is defined, as synchronizes-with or inter-thread happens-before, and the latter is defined as

for some evaluation X,

— A synchronizes with X and X is sequenced before B, or

— A is sequenced before X and X inter-thread happens before B, or

— A inter-thread happens before X and X inter-thread happens before B.

So yes, it is perfectly transitive across multiple threads. In particular, in your case,

1 sequenced-before 2

2 synchronizes-with 3

3 sequenced-before 5

5 synchronizes-with 6

6 sequenced-before 7

Therefore, 1 happens-before 7, therefore 1 is a visible side-effect with respect to 7, and therefore the value of non-atomic scalar object X as determined by the value computation of X (your "Read at X") is guaranteed to be the value stored by the visible side-effect 1.


问:
How do I test my code in Python other than by doing it by hand?
I am used to user testing in Java, and I also manually test each section of code I write, but now, I want to automate it.

There is no GUI for this project, so user testing is not required and I can focus code testing. The fact is, I don't know how to test code other than by calling the methods by hand, passing different parameters to them, and check the return value.

I suppose automation is a solution, but don't have a clue how to pass from manual testing to automated one. Are there tools which can create the relevant tests for me, or do I need to write tests manually? What can be automated?

Here is an example of code I want to test. Do I need to transform it somehow in order for it to be unit tested?

```<code>def netInfoToSend(tm, our_or_ip_version, our_or_addr_len, our_op_ip, version_their_ips,
                  num_their_ips, len_their_ips, their_ips):

    cellNetInfopkt = struct.pack(">I", time.time())

    #         Number of addresses    [1 byte]
    # cellNetInfopkt += struct.pack("B", num_their_ips)
    #         Their OR's addresses    [variable]
    print "peerAddress", peerAddress
    print "peerAddress type", type(peerAddress)

    cellNetInfopkt += struct.pack(">B", 4)
    cellNetInfopkt += struct.pack(">B", 4)
    cellNetInfopkt += struct.pack("B" * len(peerAddress), *peerAddress)

    cellNetInfopkt += struct.pack(">B", 1)

    # Address format is a type/length/value
    #         This OR's address     [variable]
    cellNetInfopkt += struct.pack(">B", our_or_ip_version) # IPV4
    cellNetInfopkt += struct.pack(">B", our_or_addr_len)
    cellNetInfopkt += struct.pack("B" * len(ownAddress), *ownAddress)

    return cellNetInfopkt
</code>```

答:
Method to test

The method takes several arguments and returns a value, without using global state nor calling other parts of the application. It does one and one only thing.

This is a good start.

If the method was using global variables, testing could be difficult.

If the method was using other parts of the application, you could be forced to use mocks or stubs.

If the method did several things, testing would quickly become a mess. You would have to refactor the code in order to create multiple methods, each one in charge of a single task, and test them separately.

Testing framework

Running unit tests can be as simple as writing a Python script which will call a bunch of methods and compare their output with the one which is expected. But don't do that. Instead, you can use a unit tests framework. While not mandatory, it will simplify your life later. The most basic framework will:

Provide you with methods like assertEqual or assertNotIn.

Some will have more of such methods; others—less. The only one you need is an ordinary assert of a condition, but additional methods can be very handy. For example, .NET has an impressive range of assertions related to collections, which helps avoiding to reinvent the wheel every time you work with collections in tests.

Run the tests in your place.

This becomes very handy in some situations, such as when one of your tests throws an exception. A testing framework automatically handles that, records the test as failed (unless the exception is expected) and runs other tests.

Show the results in a form which helps understanding how many tests passed and which ones failed.

Some integrate well into an IDE, making it visually attractive to use. If you work mostly in a terminal, all testing frameworks are able to display the results in a terminal.

The benefits of a testing framework doesn't stop here. For example:

Some frameworks can easily be extended to include code coverage.

Others integrate well with your Continuous Integration environment.

Every serious framework will include features such as code to run before or after running every test (setup and shutdown code) or specific statements which indicate that a test should throw an exception.

I hope you're convinced now that you need a framework. But previously, I provided a link to the list of some unit tests frameworks for Python, so which one to chose? It's up to you: some will have features which others don't have; some will integrate better with different environments. unittest is a good start for two reasons:

It's already installed on your machine.

It has everything you need at the beginning, and you may never need anything other.

But feel free to pick a different framework if you discover it has a feature you think you will need later.

Testing ordinary cases

Now that you have a framework, start by testing ordinary cases of your method.

What are those ordinary cases? For example, if somebody was implementing abs method which determines an absolute value of a number, ordinary testing cases would be:

```<code>def test_positive(self):
    actual = demo.abs(3)
    expected = 3
    self.assertEqual(expected, actual)

def test_negative(self):
    actual = demo.abs(-7)
    expected = 7
    self.assertEqual(expected, actual)

def test_float(self):
    actual = demo.abs(-2.91)
    expected = 2.91
    self.assertEqual(expected, actual)
</code>```

When writing the very first test, you may be blocked: how do you know whether the value returned by the method is correct?

First, if you don't want to do binary comparison and want to deal with more humanly-readable values (are they?), you can use binascii.hexlify.

As for determining the expected value, either you can use a third party application which will do the same as what your method does, or you compute one by hand. In both cases, if the test fails, you should ask yourself if your code is wrong or if the expected value is.

Remember, you don't need to test every possible input value. Not only you can't in most cases, but also, there is practically no benefit in doing it. For example, once I tested abs with a value of 3, I don't need to test it with the value of 4, then 5, then 6. I'm confident that either abs will fail with 3 (for example by throwing an exception or returning -3 or 0), or it will work for any other positive integers as well.

Looking at the code, i.e. performing white-box testing, is helpful here. If you see that the method has somewhere in it if x > 100, then you may be confident that you should test the method with at least one x inferior to 100 and one superior to it. But don't rely on the actual implementation of the code you test too often: black-box testing is often much more effective and reduces the risk of reproducing in tests the bug in the code. If you find yourself relying on actual implementation too much, test driven development can help.

Testing edge cases

Once those tests pass, you need to think about edge cases, the sort of cases which are not necessarily frequent and can eventually correspond to the situations which were missed by the author of the code to test.

Example:

```<code>def test_zero(self):
    actual = demo.abs(0)
    expected = 0
    self.assertEqual(expected, actual)

def test_nan(self):
    with self.assertRaises(ValueError):
        demo.abs(float("nan"))

def test_wrong_type(self):
    with self.assertRaises(TypeError):
        demo.abs("I'm not really a number.")

def test_none(self):
    with self.assertRaises(ValueError):
        demo.abs(None)
</code>```

When you search for edge cases, act like a hacker: imagine you want to break the method, and you want to find cases which the original author didn't expected.

If the method expects a string, what if you pass a 1 000 000 000 characters-long string? What if you pass an empty one? What if you use a different Unicode normalization form or if the string you pass to the method contains no printable characters?

If the method expects a float, floating-point rules can be tricky in some languages and should be tested as well.

Automation

You may have noticed that I haven't used the term of "automated testing". This is because there is no such a thing as manual testing. When you play with the application, searching by hand things which may fail, it's experimentation, not testing. Both tasks have a goal of discovering bugs, but they are very different.

The major benefit of real tests (compared to experimentation) is especially noticeable when it comes to regression testing, i.e. when you need to run the same tests again and again over time to ensure that new changes haven't broken anything.

A year ago, I was contributing to a project for a multinational company. The company working on the project was not using any testing, because they considered it a waste of time. The multinational company had "testers" who struggled with the web interface of the project, filling forms by hand and watching the result.

This was a five pages project and they had two "testers". At the beginning, everything was good. Quickly, the "testers" were unable to follow: with more than ten deployments per day and more than hundred bugs (some taking a long time to reproduce by hand), it was absolutely impossible to test every case.

When they were finding, randomly, that old bugs were reappearing, it was often bugs reintroduced days or weeks ago. Such regressions are extremely difficult and slow to solve, delaying the final release for months.

This story clearly shows that "testing by hand" doesn't work. It might work for tiny projects developed in a short period of time and not maintained later. But those projects usually can stay untested.

Once you have your tests, your project is partially automated. In order to run every of a few thousand tests, the only thing you need is to run a command or click on a button and then wait.

But clicking on a button is a complex task as well. One day you forget to run the tests before/after every commit. The next day, you run the tests only once. A week later, you notice that you haven't run the tests for a few days, and when you do it, the number of failed tests is overwhelming: instead of fixing them, you simply remove all the tests and continue the project without testing.

In order to avoid testing decay, there are a few hints:

Use full automation, i.e. integrate tests into Continuous Integration.

If tests fail, fixing them should be your top priority.

Commit frequently. I often see programmers who barely do one commit per day, when they leave their desk in evening (and sometimes can disappear from version control log for a few days). They do it wrong.

Ensure tests don't take hours to run (or that you can run them selectively while being confident that all tests potentially concerned by the recent changes are run).

Those three hints help making testing as painless as possible by making it a constant process as much as possible. With short iterations, you are notified quickly about failed tests and you solve them quickly: the more you wait, the more expensive and difficult the task would be.

Using regression testing has also an important benefit: if you know that mistakes in code will be easy to solve, you will be able to refactor code much more intensively. You can try it yourself: your NetInfoToSend contains code duplication; try to remove it.

The cake is a lie

The last part is more the response to "create the tests for me" in your question. Researching about tests, you'll find lots of products advertised as being THE solution to unit testing. Advertisement will assert that the product will write the tests for you, or improve your productivity by 100 or make you happy in any other way.

Don't trust them.

Some tools are helpful, but their importance is relative.

Unit test frameworks help, but they do nothing you can do manually.

Code coverage help finding parts which are not covered enough, but tools are stupid enough to put a red flag on boilerplate code where unit tests are useless anyway, or to make you feel safe when you reach 98% code coverage on business-critical code which requires 99.95%.

Tools creating unit tests for you may help in some cases, but they can focus on code which you don't necessarily need to test and leave aside the three lines of code you would like to test the most. I'm not saying tools such as Pex are useless: they are excellent at what they do, but they shouldn't replace you as a tester.

Body:
Method to test

The method takes several arguments and returns a value, without using global state nor calling other parts of the application. It does one and one only thing.

This is a good start.

If the method was using global variables, testing could be difficult.

If the method was using other parts of the application, you could be forced to use mocks or stubs.

If the method did several things, testing would quickly become a mess. You would have to refactor the code in order to create multiple methods, each one in charge of a single task, and test them separately.

Testing framework

Running unit tests can be as simple as writing a Python script which will call a bunch of methods and compare their output with the one which is expected. But don't do that. Instead, you can use a unit tests framework. While not mandatory, it will simplify your life later. The most basic framework will:

Provide you with methods like assertEqual or assertNotIn.

Some will have more of such methods; others—less. The only one you need is an ordinary assert of a condition, but additional methods can be very handy. For example, .NET has an impressive range of assertions related to collections, which helps avoiding to reinvent the wheel every time you work with collections in tests.

Run the tests in your place.

This becomes very handy in some situations, such as when one of your tests throws an exception. A testing framework automatically handles that, records the test as failed (unless the exception is expected) and runs other tests.

Show the results in a form which helps understanding how many tests passed and which ones failed.

Some integrate well into an IDE, making it visually attractive to use. If you work mostly in a terminal, all testing frameworks are able to display the results in a terminal.

The benefits of a testing framework doesn't stop here. For example:

Some frameworks can easily be extended to include code coverage.

Others integrate well with your Continuous Integration environment.

Every serious framework will include features such as code to run before or after running every test (setup and shutdown code) or specific statements which indicate that a test should throw an exception.

I hope you're convinced now that you need a framework. But previously, I provided a link to the list of some unit tests frameworks for Python, so which one to chose? It's up to you: some will have features which others don't have; some will integrate better with different environments. unittest is a good start for two reasons:

It's already installed on your machine.

It has everything you need at the beginning, and you may never need anything other.

But feel free to pick a different framework if you discover it has a feature you think you will need later.

Testing ordinary cases

Now that you have a framework, start by testing ordinary cases of your method.

What are those ordinary cases? For example, if somebody was implementing abs method which determines an absolute value of a number, ordinary testing cases would be:

def test_positive(self):
    actual = demo.abs(3)
    expected = 3
    self.assertEqual(expected, actual)

def test_negative(self):
    actual = demo.abs(-7)
    expected = 7
    self.assertEqual(expected, actual)

def test_float(self):
    actual = demo.abs(-2.91)
    expected = 2.91
    self.assertEqual(expected, actual)

When writing the very first test, you may be blocked: how do you know whether the value returned by the method is correct?

First, if you don't want to do binary comparison and want to deal with more humanly-readable values (are they?), you can use binascii.hexlify.

As for determining the expected value, either you can use a third party application which will do the same as what your method does, or you compute one by hand. In both cases, if the test fails, you should ask yourself if your code is wrong or if the expected value is.

Remember, you don't need to test every possible input value. Not only you can't in most cases, but also, there is practically no benefit in doing it. For example, once I tested abs with a value of 3, I don't need to test it with the value of 4, then 5, then 6. I'm confident that either abs will fail with 3 (for example by throwing an exception or returning -3 or 0), or it will work for any other positive integers as well.

Looking at the code, i.e. performing white-box testing, is helpful here. If you see that the method has somewhere in it if x > 100, then you may be confident that you should test the method with at least one x inferior to 100 and one superior to it. But don't rely on the actual implementation of the code you test too often: black-box testing is often much more effective and reduces the risk of reproducing in tests the bug in the code. If you find yourself relying on actual implementation too much, test driven development can help.

Testing edge cases

Once those tests pass, you need to think about edge cases, the sort of cases which are not necessarily frequent and can eventually correspond to the situations which were missed by the author of the code to test.

Example:

def test_zero(self):
    actual = demo.abs(0)
    expected = 0
    self.assertEqual(expected, actual)

def test_nan(self):
    with self.assertRaises(ValueError):
        demo.abs(float("nan"))

def test_wrong_type(self):
    with self.assertRaises(TypeError):
        demo.abs("I'm not really a number.")

def test_none(self):
    with self.assertRaises(ValueError):
        demo.abs(None)

When you search for edge cases, act like a hacker: imagine you want to break the method, and you want to find cases which the original author didn't expected.

If the method expects a string, what if you pass a 1 000 000 000 characters-long string? What if you pass an empty one? What if you use a different Unicode normalization form or if the string you pass to the method contains no printable characters?

If the method expects a float, floating-point rules can be tricky in some languages and should be tested as well.

Automation

You may have noticed that I haven't used the term of "automated testing". This is because there is no such a thing as manual testing. When you play with the application, searching by hand things which may fail, it's experimentation, not testing. Both tasks have a goal of discovering bugs, but they are very different.

The major benefit of real tests (compared to experimentation) is especially noticeable when it comes to regression testing, i.e. when you need to run the same tests again and again over time to ensure that new changes haven't broken anything.

A year ago, I was contributing to a project for a multinational company. The company working on the project was not using any testing, because they considered it a waste of time. The multinational company had "testers" who struggled with the web interface of the project, filling forms by hand and watching the result.

This was a five pages project and they had two "testers". At the beginning, everything was good. Quickly, the "testers" were unable to follow: with more than ten deployments per day and more than hundred bugs (some taking a long time to reproduce by hand), it was absolutely impossible to test every case.

When they were finding, randomly, that old bugs were reappearing, it was often bugs reintroduced days or weeks ago. Such regressions are extremely difficult and slow to solve, delaying the final release for months.

This story clearly shows that "testing by hand" doesn't work. It might work for tiny projects developed in a short period of time and not maintained later. But those projects usually can stay untested.

Once you have your tests, your project is partially automated. In order to run every of a few thousand tests, the only thing you need is to run a command or click on a button and then wait.

But clicking on a button is a complex task as well. One day you forget to run the tests before/after every commit. The next day, you run the tests only once. A week later, you notice that you haven't run the tests for a few days, and when you do it, the number of failed tests is overwhelming: instead of fixing them, you simply remove all the tests and continue the project without testing.

In order to avoid testing decay, there are a few hints:

Use full automation, i.e. integrate tests into Continuous Integration.

If tests fail, fixing them should be your top priority.

Commit frequently. I often see programmers who barely do one commit per day, when they leave their desk in evening (and sometimes can disappear from version control log for a few days). They do it wrong.

Ensure tests don't take hours to run (or that you can run them selectively while being confident that all tests potentially concerned by the recent changes are run).

Those three hints help making testing as painless as possible by making it a constant process as much as possible. With short iterations, you are notified quickly about failed tests and you solve them quickly: the more you wait, the more expensive and difficult the task would be.

Using regression testing has also an important benefit: if you know that mistakes in code will be easy to solve, you will be able to refactor code much more intensively. You can try it yourself: your NetInfoToSend contains code duplication; try to remove it.

The cake is a lie

The last part is more the response to "create the tests for me" in your question. Researching about tests, you'll find lots of products advertised as being THE solution to unit testing. Advertisement will assert that the product will write the tests for you, or improve your productivity by 100 or make you happy in any other way.

Don't trust them.

Some tools are helpful, but their importance is relative.

Unit test frameworks help, but they do nothing you can do manually.

Code coverage help finding parts which are not covered enough, but tools are stupid enough to put a red flag on boilerplate code where unit tests are useless anyway, or to make you feel safe when you reach 98% code coverage on business-critical code which requires 99.95%.

Tools creating unit tests for you may help in some cases, but they can focus on code which you don't necessarily need to test and leave aside the three lines of code you would like to test the most. I'm not saying tools such as Pex are useless: they are excellent at what they do, but they shouldn't replace you as a tester.


问:
Would you still use Java in your next project, despite the whole mess in JCP
It seems that there is a whole mess around current JCP.

Quite of number of highly respected guys like Doug Lea, Tim Peierls had quit JCP.

Reference :

Is JCP dead? and Final results of the JSR Review Ballot for JSR #336

This put Java in an unfavorable future. As a Java developer, will you still consider using Java in your next project?

答:
Yes.

The developer support will be around for a very long time.  The language is mature, most JVMs are very stable and fast.  I find little core necessary libraries or language features missing.  I would still choose Java over most other languages and runtimes still due to its ability to sell into nearly any IT ecosystem.

I wait eagerly for a new cross-platform language and runtime that can support the widest customer base, but all things considered, Java still reigns supreme.


问:
How should I approach this from a problem-solving point of view?
I'm currently working on a project to replace some excel worksheets. There is a lot of industry specifics that change quite often and nobody really knows how things should be but every sure enough thinks they know how they shouldn't be.

Project Priorities:

Maintainability - The business processes change frequently. There are like 3-5 different excel templates floating around.

Agile - My boss wants visible changes every week (sometimes less).

Structure - This application will work with several other systems for the entire business process.

Approach & Design:

The DB Schema we took was one where we defined some business logic in the database.
EntityTypes, Properties of those types, and their values are stored in the database (each having their own table ofcourse).

Now, I originally thought about the typical approach, having an Estimate Table defining its properties, Bid Table, Joist Table, etc. (Each of these are EntityTypes by the way).

My boss wanted the DBSchema we're using now (See picture).

Pros/Cons:

Current Schema:

Pros: (Theoretically) Adapts to the data allowing for later changes to be as simple as adding the data to the database.

Cons: Overly complex. I have difficulty even getting my mind around this schema when trying to create the class that will handle it.

Typical/Traditional Schema:

Pros: Simplistic, Anyone without knowledge of the project will be able to pick it up in the future.

Cons: Many Many Tables. Not what we have now.

Situation:

I am currently retrieving the data using a class I made to represent an entity, then converting them into business model classes (Estimate, Bid, Joist...) to pass to the view. This obviously is extra work for the current schema, but I felt that the other way of having the view/controller parse through the model to determine how to display the data (making us only require a few views/controllers) seemed like bad design/programming (though I'm not entirely sure why). Am I correct thinking this schema/design is bad? If, so why?

My Boss wants this Schema because "it may be complex but once the programming is done no more changes should need done." Now obviously the way I'm doing this, that's not true. If I were to do it the way he wants I feel like I might fail to do so as I kept confusing myself with the complexities.

One of my boss's arguments is that you find yourself with a lot of NULL fields when you do the traditional schema (which I feel like you're doing it wrong if that's the case. Maybe in some instances but they have tables with like 30 columns where 10+ majority of the rows have a NULL value for that column).

Will doing all the programming for supporting the current Schema the way he desires be worth the theoretical simplicity to add things in the future? It's not all that much work to add a small feature to a class, and add the display to the view's template using knockout. Especially considering the project is being done in an Agile environment and doing all the work at once then having something to show for it doesn't sound very Agile to me, which is basically what would need done to code the complex classes and display them in the views, not to mention I'd have to code a bunch of HTML helpers (coupling them a bit with Knockout) in order to do this. So personally it sounds like it's just moving the work not saving any. Am I correct in this thought process?

Proposed solution:

I suggested the other day to switch to the other schema and use Entity Framework Code-First to make changes easier (as the way I'm doing it now I have the change the Business Models regardless. Code-First would theoretically allow me to not have to do the Database Changes as well).

My boss's main concern is that with a traditional schema the schema changes and then other systems will need updated as well. Whereas, he states that if we have the current schema then the other systems won't need updated if something changes in the database. Which I don't quite understand since how would it know how to deal with the data? Wouldn't it just mean it too would need complex coding/processes to back it up initially?

Questions:

Why is this schema design bad (if it is)? How can I argue this schema design is bad?

If it is not a bad design, How can I better prepare myself for it? I do my best to Abstract classes/functionality and keep things with single responsibilities.

If it is a bad design, How can I convince my boss to switch to my suggestion (assuming my suggestion is the best/only alternative)?

I understand the last two questions are a but subjective, so it's understandable if they are ignored.

答:
To be honest excel spreadsheets are a better solution than the proposed database.

Maybe you could recommend a hybrid approach to your boss.

Its unlikely that you will get a new Entity (i.e. basic object type) that often so have a table for each basic object type.

Each Entity/Object will have a number of attributes/fields which are basic to that object and will never change -- define these as columns in your table.

Each entity will however have Attributes/Fields which are highly volatile depending on the current business requirement -- leverage the XML capabilities of any modern DBMS and store these within XML columns which can happliy hold key/value pairs, hash tables, object trees or all manner of structures without requiring a change to the underlying database schema. If you do not like XML a CLOB string holding a JSON object can work just as well.

At the very least if your boss insists on the current proposal get a NoSql database which is designed for this sort of thing.


答:
The fact is, I don't know how to test code other than by calling the
  methods by hand, passing different parameters to them, and check the
  return value.

That's exactly how we test code. When we automate tests, we don't automate writing tests, we automate executing them. Basically, write code that calls your function and checks that it gives the correct results. When you write that code using a unit testing framework, you can easily run all the tests you've written in the past to make sure it still works.

Are there tools which can create the relevant tests for me, or do I
  need to write tests manually?

There are tools that can produce unit tests, but you really shouldn't think about using them until you are very comfortable with automated testing. Instead, write the test manually.

As for your actual code, there some oddity there. You don't appear to use most of the parameters you are passing in. But I'd write a test something like:

```<code>from nose.tools import assert_equal

def test_netInfoToSend():
    assert_equal("\x24\x25\x345\x34\x345", netInfoToSend(2, 3, 5, 5))
</code>```

I use nose for unit testing in python. Now when I run the nosetests command, that test will run and I'll know that netInfoSend still returns the correct result.

One tricky bit with testing your code is that you call time.time(), which means that your function won't always return the same result. There are a few ways of dealing with that:

Firstly, you can replace time.time with your own functions: time.time = lambda: 2000 and it will always return the same result. However, you have to make sure that you put the original time.time function back after you are done.

Secondly, you can pass the time into your function. So instead of the function calling time.time(), whatever calls the function can call it. Since the function is concerned with packing values into a string that might make sense.

Thirdly, you use dependency injection. This is probably the best solution, but is a big topic. You'll to look elsewhere to read about it.

Title: How do I test my code in Python other than by doing it by hand?

Body:
I am used to user testing in Java, and I also manually test each section of code I write, but now, I want to automate it.

There is no GUI for this project, so user testing is not required and I can focus code testing. The fact is, I don't know how to test code other than by calling the methods by hand, passing different parameters to them, and check the return value.

I suppose automation is a solution, but don't have a clue how to pass from manual testing to automated one. Are there tools which can create the relevant tests for me, or do I need to write tests manually? What can be automated?

Here is an example of code I want to test. Do I need to transform it somehow in order for it to be unit tested?

```<code>def netInfoToSend(tm, our_or_ip_version, our_or_addr_len, our_op_ip, version_their_ips,
                  num_their_ips, len_their_ips, their_ips):

    cellNetInfopkt = struct.pack(">I", time.time())

    #         Number of addresses    [1 byte]
    # cellNetInfopkt += struct.pack("B", num_their_ips)
    #         Their OR's addresses    [variable]
    print "peerAddress", peerAddress
    print "peerAddress type", type(peerAddress)

    cellNetInfopkt += struct.pack(">B", 4)
    cellNetInfopkt += struct.pack(">B", 4)
    cellNetInfopkt += struct.pack("B" * len(peerAddress), *peerAddress)

    cellNetInfopkt += struct.pack(">B", 1)

    # Address format is a type/length/value
    #         This OR's address     [variable]
    cellNetInfopkt += struct.pack(">B", our_or_ip_version) # IPV4
    cellNetInfopkt += struct.pack(">B", our_or_addr_len)
    cellNetInfopkt += struct.pack("B" * len(ownAddress), *ownAddress)

    return cellNetInfopkt
</code>```

Body:
The fact is, I don't know how to test code other than by calling the
  methods by hand, passing different parameters to them, and check the
  return value.

That's exactly how we test code. When we automate tests, we don't automate writing tests, we automate executing them. Basically, write code that calls your function and checks that it gives the correct results. When you write that code using a unit testing framework, you can easily run all the tests you've written in the past to make sure it still works.

Are there tools which can create the relevant tests for me, or do I
  need to write tests manually?

There are tools that can produce unit tests, but you really shouldn't think about using them until you are very comfortable with automated testing. Instead, write the test manually.

As for your actual code, there some oddity there. You don't appear to use most of the parameters you are passing in. But I'd write a test something like:

from nose.tools import assert_equal

def test_netInfoToSend():
    assert_equal("\x24\x25\x345\x34\x345", netInfoToSend(2, 3, 5, 5))

I use nose for unit testing in python. Now when I run the nosetests command, that test will run and I'll know that netInfoSend still returns the correct result.

One tricky bit with testing your code is that you call time.time(), which means that your function won't always return the same result. There are a few ways of dealing with that:

Firstly, you can replace time.time with your own functions: time.time = lambda: 2000 and it will always return the same result. However, you have to make sure that you put the original time.time function back after you are done.

Secondly, you can pass the time into your function. So instead of the function calling time.time(), whatever calls the function can call it. Since the function is concerned with packing values into a string that might make sense.

Thirdly, you use dependency injection. This is probably the best solution, but is a big topic. You'll to look elsewhere to read about it.


问:
OnClickListener good practice
Which one of the ways has better performance, or  is a good programming practice, making the holder activity extend OnClickListener and make a Switch() clause for getItemId() or making one OnClickListener for each one of the buttons or widgets that need it or making separated classes in the same (or another) package that implements OnClickListener and instance them in the activity?

答:
Here are the best and better programming way for to work with button /any other widget

Declare Button/ any other widgets Object outside from the Activity life cycle method; mostly after declaration of the public class like this

public class MainActivity extends Activity {

Button button;

Always define inside the onCreate(Bundle savedInstanceState) method; because it's guaranteed that onCreate() always call so therefore it's better to define inside onCreate() method.

Here is the complete Code example

```<code>public class MainActivity extends Activity {

Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button=(Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //Any thing you want here
        }
    });

}
</code>```

On the above I have used anonymous class onClickLListener that is the nested class of View class; so you can also use separate class
Avoid to make switch statement because it's make your like spaghetti like.

Title: OnClickListener good practice

Body:
Here are the best and better programming way for to work with button /any other widget

Declare Button/ any other widgets Object outside from the Activity life cycle method; mostly after declaration of the public class like this

public class MainActivity extends Activity {

Button button;

Always define inside the onCreate(Bundle savedInstanceState) method; because it's guaranteed that onCreate() always call so therefore it's better to define inside onCreate() method.

Here is the complete Code example

public class MainActivity extends Activity {

Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button=(Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //Any thing you want here
        }
    });

}

On the above I have used anonymous class onClickLListener that is the nested class of View class; so you can also use separate class
Avoid to make switch statement because it's make your like spaghetti like.


答:
Yes, I would. Java is one of the most widely spread programming languages so Java will exist for a long time.

I don't think it's many languages that can compete with Java as of today. It has a huge userbase and big libraries, both standard libraries and third party libraries. It has good performance with garbage collection. And it has static typing.

If you look at TIOBE Index and want a static typed object oriented language with managed memory, many good libraries and target multiple platforms. Then I think Java is still the best choice.

Java is that big so it will not die even if Oracle try to kill it very hard. I think that Google will release a similar and compatible language under a different name if it get worse. It's so big that it can't die.

And it is a good language compared to many alternatives. Oracle will just make it a more commercial language than before. And C#, the best alternative is also a commercial language, so it doesn't mean that the language will die, it will just be different.

Title: Would you still use Java in your next project, despite the whole mess in JCP

Body:
It seems that there is a whole mess around current JCP.

Quite of number of highly respected guys like Doug Lea, Tim Peierls had quit JCP.

Reference :

Is JCP dead? and Final results of the JSR Review Ballot for JSR #336

This put Java in an unfavorable future. As a Java developer, will you still consider using Java in your next project?


问:
How would you create a program where two objects randomly move throughout the screen BUT never collide?
they are free to move anywhere on the screen weather in straight lines or curved ones just as long as they don't be at the same place at any given time.

btw I'm not asking how to write it in code, but rather the logic if you will?
1- how would you make an object move randomly? (disregarding predefined functions or classes..etc)
2-how do you ensure they never hit?

答:
From a physics perspective, collision is just an extreme case of a repulsive force between objects.  If you want them to automatically avoid each other, a simple way would be to introduce a gradual force that repels them depending on how close they are to each other.  For example, electrical forces satisfy

```<code>force ∝ 1 / distance^2
</code>```

Since this doesn't need to be physical, you can tweak the coefficient and/or exponent however you wish to make the objects better at avoiding each other.  It doesn't need to obey a power law either, you can introduce any complicated force field as long as it's repulsive:

```<code>force = f(d) R
</code>```

where d is the separation distance, f is a function that becomes increasingly large near 0, and R is the unit vector that defines the direction between the two objects.

From a different angle, if you can control the "randomness" of the motion, you can also influence it in such a way that they will never hit each other, but this requires your program to be able to predict the motion of other object.

There are many different kinds of "random" motion: you may want to be specific as to what kind you are interested in.  If you want the motion to appear continuous and smooth, you can add random but small changes to the velocity vector (i.e. the magnitude and direction) at every frame of the animation.  Or if you want it to be jerky, you can make the random changes more drastic.

Body:
From a physics perspective, collision is just an extreme case of a repulsive force between objects.  If you want them to automatically avoid each other, a simple way would be to introduce a gradual force that repels them depending on how close they are to each other.  For example, electrical forces satisfy

force ∝ 1 / distance^2

Since this doesn't need to be physical, you can tweak the coefficient and/or exponent however you wish to make the objects better at avoiding each other.  It doesn't need to obey a power law either, you can introduce any complicated force field as long as it's repulsive:

force = f(d) R

where d is the separation distance, f is a function that becomes increasingly large near 0, and R is the unit vector that defines the direction between the two objects.

From a different angle, if you can control the "randomness" of the motion, you can also influence it in such a way that they will never hit each other, but this requires your program to be able to predict the motion of other object.

There are many different kinds of "random" motion: you may want to be specific as to what kind you are interested in.  If you want the motion to appear continuous and smooth, you can add random but small changes to the velocity vector (i.e. the magnitude and direction) at every frame of the animation.  Or if you want it to be jerky, you can make the random changes more drastic.


问:
Type inference in Golang/Haskell
I've read that Go doesn't actually have true type inference in the sense that functional languages such as ML or Haskell have, but I haven't been able to find a simple to understand comparison of the two versions. Could someone explain in basic terms how type inference in Go differs from type inference in Haskell, and the pros/cons of each?</p>

答:
See this StackOverflow answer regarding Go's type inference.  I'm not familiar with Go myself but based on this answer it seems like a one-way "type deduction" (to borrow some C++ teminology).  It means that if you have:

x := y + z
```

<p>then the type of <code>x</code> is deduced by figuring out the type of <code>y + z</code>, which is a relatively trivial thing to do for the compiler.  To do this, the types of <code>y</code> and <code>z</code> need to be known <em>a priori</em>: this could be done via type annotations or inferred from the literals assigned to them.</p>

<hr>

<p>In contrast, most functional languages have type inference that uses all possible information within a module (or function, if the inference algorithm is local) to derive the type of the variables.  Complicated inference algorithms (such as Hindley-Milner) often involve some form of type <em>unification</em> (a bit like solving equations) behind the scenes. For example, in Haskell, if you write:</p>

```let x = y + z
```

<p>then Haskell can infer the type not just <code>x</code> but also <code>y</code> and <code>z</code> simply based on the fact that you're performing addition on them.  In this case:</p>

```x :: Num a => a
y :: Num a => a
z :: Num a => a
```

<p>(The lowercase <code>a</code> here denotes a <em>polymorphic type</em>, often called "generics" in other languages like C++.  The <code>Num a =></code> part is a <em>constraint</em> to indicate that the type <code>a</code> support have some notion of addition.)</p>

<p>Here's a more interesting example: the fixed-point combinator that allows any recursive function to be defined:</p>

```let fix f = f (fix f)
```

<p>Notice that nowhere have we specified the type of <code>f</code>, nor did we specify the type of <code>fix</code>, yet the Haskell compiler can automatically figure out that:</p>

```f :: t -> t
fix :: (t -> t) -> t
```

This says that:

The parameter f must be a function from some arbitrary type t to the same type t.

fix is a function that receives a parameter of type t -> t and returns a result of type t.

Title: Type inference in Golang/Haskell

Body:
See this StackOverflow answer regarding Go's type inference.  I'm not familiar with Go myself but based on this answer it seems like a one-way "type deduction" (to borrow some C++ teminology).  It means that if you have:

x := y + z

then the type of x is deduced by figuring out the type of y + z, which is a relatively trivial thing to do for the compiler.  To do this, the types of y and z need to be known a priori: this could be done via type annotations or inferred from the literals assigned to them.

In contrast, most functional languages have type inference that uses all possible information within a module (or function, if the inference algorithm is local) to derive the type of the variables.  Complicated inference algorithms (such as Hindley-Milner) often involve some form of type unification (a bit like solving equations) behind the scenes. For example, in Haskell, if you write:

let x = y + z

then Haskell can infer the type not just x but also y and z simply based on the fact that you're performing addition on them.  In this case:

x :: Num a => a
y :: Num a => a
z :: Num a => a

(The lowercase a here denotes a polymorphic type, often called "generics" in other languages like C++.  The Num a => part is a constraint to indicate that the type a support have some notion of addition.)

Here's a more interesting example: the fixed-point combinator that allows any recursive function to be defined:

let fix f = f (fix f)

Notice that nowhere have we specified the type of f, nor did we specify the type of fix, yet the Haskell compiler can automatically figure out that:

f :: t -> t
fix :: (t -> t) -> t

This says that:

The parameter f must be a function from some arbitrary type t to the same type t.

fix is a function that receives a parameter of type t -> t and returns a result of type t.


答:
Type inference in Go is extremely limited and extremely simple. It works only in one language construct (variable declaration) and it simply takes the type of the right-hand side and uses it as the type for the variable on the left-hand side.

Type inference in Haskell can be used everywhere, it can be used to infer the types for the whole program. It is based on unification, which means that (conceptually) all types are inferred "at once" and they can all influence each other: in Go, type information can only flow from the right-hand side of a variable declaration to the left-hand side, never in the other direction and never outside of a variable declaration; in Haskell, type information flows freely in all directions through the entire program.

However, Haskell's type system is so powerful that type inference can actually fail to infer a type (or more precisely: restrictions have to be put in place so that a type can always be inferred). Go's type system is so simple (no subtyping, no parametric polymorphism) and its inference so limited that it always succeeds.

Title: Type inference in Golang/Haskell

Body: I've read that Go doesn't actually have true type inference in the sense that functional languages such as ML or Haskell have, but I haven't been able to find a simple to understand comparison of the two versions. Could someone explain in basic terms how type inference in Go differs from type inference in Haskell, and the pros/cons of each?</p>


问:
Where should the "not empty field" validation code be written on a 3-layer application?
When working with the 3-layer model, where should the validation code be placed? for: not empty fields, unchecked options, null values, wrong-written dates, etc.

To keep total isolation between a form (UI layer) and the business rules, this validation should belong to BLL?

It's the only work for the UI: grab user data input, without any care of verifying, and just send it to next layer.

For example, It's an empty username field, really breaking a business rule, or the BLL doesn't even need to care about getting empty values, sure, UI takes care.

Could be this shallow validation, considered as an actual BL rule, or is enough handle it on UI layer?

答:
It depends on what your requirements are, but for maximum robustness validation at the backend is preferred, but that does not preclude validation in the frontend as well.

Do you care if bad input gets into the system?  Will it wreak havoc?  If so then you definitely should validate in the backend, unless you are absolutely sure that there's no way for the bad input to sneak past the frontend validations.

What feedback will the user receive if validation fails?  Inevitably, in order to construct helpful error messages your user interface will need to have some knowledge of what's wrong with the input unless your users are okay a generic "ERROR: BAD INPUT".  Now, you probably won't need to duplicate the full logic here if you design it well, but this also depends on how much assistance you want to give to the user.


问:
Keep a programming language backwards compatible vs. fixing its flaws
First, some context (stuff that most of you know anyway):

Every popular programming language has a clear evolution, most of the time marked by its version: you have Java 5, 6, 7 etc., PHP 5.1, 5.2, 5.3 etc. Releasing a new version makes new APIs available, fixes bugs, adds new features, new frameworks etc. So all in all: it's good.

But what about the language's (or platform's) problems? If and when there's something wrong in a language, developers either avoid it (if they can) or they learn to live with it.

Now, the developers of those languages get a lot of feedback from the programmers that use them. So it kind of makes sense that, as time (and version numbers) goes by, the problems in those languages will slowly but surely go away. Well, not really. Why? Backwards compatibility, that's why. But why is this so? Read below for a more concrete situation.

The best way I can explain my question is to use PHP as an example:

PHP is loved, and hated by thousands of people. All languages have flaws, but apparently PHP is special. Check out this blog post. It has a very long list of so called flaws in PHP. Now, I'm not a PHP developer (not yet), but I read through all of it and I'm sure that a big chunk of that list are indeed real issues. (Not all of it, since it's potentially subjective).

Now, if I was one of the guys who actively develops PHP, I would surely want to fix those problems, one by one. However, if I do that, then code that relies on a particular behavior of the language will break if it runs on the new version. Summing it up in 2 words: backwards compatibility.

What I don't understand is: why should I keep PHP backwards compatible? If I release PHP version 8 with all those problems fixed, can't I just put a big warning on it saying: "Don't run old code on this version !"?

There is a thing called deprecation. We had it for years and it works. In the context of PHP: look at how these days people actively discourage the use of the mysql_* functions (and instead recommend mysqli_* and PDO). Deprecation works. We can use it. We should use it. If it works for functions, why shouldn't it work for entire languages?

Let's say I (the developer of PHP) do this:

Launch a new version of PHP (let's say 8) with all of those flaws fixed

New projects will start using that version, since it's much better, clearer, more secure etc.

However, in order not to abandon older versions of PHP, I keep releasing updates to it, fixing security issues, bugs etc. This makes sense for reasons that I'm not listing here. It's common practice: look for example at how Oracle kept updating version 5.1.x of MySQL, even though it mostly focused on version 5.5.x.

After about 3 or 4 years, I stop updating old versions of PHP and leave them to die. This is fine, since in those 3 or 4 years, most projects will have switched to PHP 8 anyway.

My question is: Do all these steps make sense? Would it be so hard to do? If it can be done, then why isn't it done?

Yes, the downside is that you break backwards compatibility. But isn't that a price worth paying ? As an upside, in 3 or 4 years you'll have a language that has 90 % of its problems fixed.... a language much more pleasant to work with. Its name will ensure its popularity.

EDIT: OK, so I didn't expressed myself correctly when I said that in 3 or 4 years people will move to the hypothetical PHP 8. What I meant was: in 3 or 4 years, people will use PHP 8 if they start a new project.

答:
It's best to never break backwards compatibility.

Microsoft replaced the VB6 programming language with a new language that totally broke compatibility. So even today the 16 year old VB6 is still more popular than the dotNet version (Tiobe index August 2014). And Gartner estimates there are 14 billion lines of VB6 code still in use.

In 2014 Microsoft have again had to announce they will not update or open source VB6 despite demands from the Visual Basic programming community.
But they have extended support of VB6 until 'at least' 2024, and it works fine on Windows 7 and 8. That will be over 26 years of support for the same version of VB6.

Why should existing working software have to be re-written, even Microsoft never "updated" Office to use dotNet ?


答:
As encountered on multiple websites where it is asked to fill-in a form, you often see obligatory fields. Such fields are often validated through Javascript for non-emptyness and all-numeric inputs, for instance.

Yes, it is better to have the back-end do the dirty job, but the UI makes sure that the information input is provided, then the input is further validated in the back-end code.

MVC

In an MVC application, you'll have the view validates for obligatory empty fields and the UI shall not allow for blank input into obligatory fields. Then, once the mandatory information is provided, it belongs to the controller to send along the information to the model for proper validation.

For more information on the MVC architecture pattern, you may pay a visit to Martin Fowler's website on the topic.

MVP

In an MVP application, you'll have the two approaches: Supervising Controller and Passive View.

Supervising Controller

The view is aware of certain rules such as enabling a button once all required fields have been filled in properly. Even for format validation! For instance, your view shall present proper controls for different inputs such as a drop-down calendar, a combo-box, a numeric-up-down, etc. Then, it makes sure to enable the submit button only and only if all required information is filled in.

Passive View

The view is a dumb. It all passes on the information right to the Presenter which validates in the back-end whether the information is good or not. It's easy to setup such a Passive View pattern in Windows Forms application or the like, but clearly misleading (IMHO) in a web application.

MVVM

The view and the view-model are bound together so that the view-model may state whether it's all required fields have been filled in correctly and act upon the view accordingly. Besides, it is far more preferable, to my point of view, to let the view the possibility, for example, to whether enable a button when the information in itself changes, based on the view-model state. That is the view that reads the view-model state, and the view-model shall then tell the view whether the button shall be enabled or not.

There are also more architecture patterns which handles different things differently. They all have their benefits and trade-offs. MVVM is great for WPF application, and MVP is best for Webforms application, as MVC is best for Web application in general. You may even prefer to use a hybrid approach such as MVP-C-VM, etc. based on your knowledge and expertise. The idea is to keep the code as simple as it can, and easy to maintain as it can. So basically, it is finally quite a matter of preference based on your expertise and experience.

In the end, as far as I'm concerned, I like best to have some basic validations directly in the view (UI-layer) to offer a better user experience and avoid some lags that can occur with the back-end. Then, when the user actually submits the information, a more robust validation can occur.

Title: Where should the "not empty field" validation code be written on a 3-layer application?

Body:
When working with the 3-layer model, where should the validation code be placed? for: not empty fields, unchecked options, null values, wrong-written dates, etc.

To keep total isolation between a form (UI layer) and the business rules, this validation should belong to BLL?

It's the only work for the UI: grab user data input, without any care of verifying, and just send it to next layer.

For example, It's an empty username field, really breaking a business rule, or the BLL doesn't even need to care about getting empty values, sure, UI takes care.

Could be this shallow validation, considered as an actual BL rule, or is enough handle it on UI layer?


答: If they can randomly move on a straight liner simply let both of them move randomly right and left while not being on the same height. </p>

Title: How would you create a program where two objects randomly move throughout the screen BUT never collide?

Body:
they are free to move anywhere on the screen weather in straight lines or curved ones just as long as they don't be at the same place at any given time.

btw I'm not asking how to write it in code, but rather the logic if you will?
1- how would you make an object move randomly? (disregarding predefined functions or classes..etc)
2-how do you ensure they never hit?


问:
Why we need Throw-away Prototyping?
What is throw-away prototyping model in software engineering and why do we need it? How does it differentiate from Evolutionary Prototyping?</p>

答:
Prototyping is used for many reasons. Maybe you want to gauge the user experience to a new application to estimate whether it's worth building, without incurring the expense of actually building it. Maybe you need something that talks to an existing program over the network to perform integration or load tests on your network, before you've had time to finish the actual software running on your node. Maybe you need to show your investors something that looks almost like a finished program so that they'll be more willing to come up with the investment needed to actually finish the program. (This has nothing to do with deception. Users and managers judge software solely by its interface, so it's important to present them with a good interface so that they will believe the project is as far along as it actually is.)

A throwaway prototype is simply one that will not be incrementally transformed into the actual solution, but replaced by a new-written one. Obviously there is some waste involved in throwing away code that already does at least some of what you want, but the better architectural integrity of the proper code can easily offset that disadvantage.

Title: Why we need Throw-away Prototyping?