问:
Why are part-time jobs in programming an anomaly?
I've recently quit my full time developing job at mega-corp, and I decided that I'll look for a part time job. Since then I've talked to half a dozen potential employers, and every one of them had the same reaction when I said the magic words "part-time" - they all closed up and became suspicious. Now, I understand that it might just be me, so as control I asked every one of them what if I were willing to work full time, and they all said I would probably get an offer.

My question is two fold:

Why, as an employer, would you give up a competent, even great, developer, simply because he wants to work 3 days a week and not 5?

How do I sell the story of part time job better? I usually just list my reasons which are that I prefer that balance currently in my life and that I want to work on my own projects, but it leaves them even more suspicious - am I going to start something myself and quit? Am I just lazy?

答:
The points about efficiency and overhead (both bureaucratic and in the N^2 interpersonal effects) seem valid, but here's a more jaded take: employers of coders don't want any limitation at all on the hours they can ask of you.   They're used to being able to ask developers to work 50, 60, in my experience as much as 80 hours in some weeks for no extra pay (and on hourly contracts to lie about your hours, or it's go look for another job...which eventually I did do, but many can't or in any event won't).   Someone who starts by limiting their hours to a nominal (say) 24/wk doesn't sound like someone who will be willing to work  40 for the same wages when asked to so do,  for reasons decent (deadlines)  and indecent ('We need the shares price to rise a few pennies for a few weeks, so let's fire a few people and let the others, cowed by the firings, take on the work their former colleagues performed, ').

Note: if you've a reputation as a wizard,  you can in fact get part-time work, as some will feel blessed that they get any of you at all---this is related to why rock-stars tend to have a lot of casual sex (because they can, because enough potential partners value such so, and because social norms are actually enforced by allowing exceptional people to violate them---'Sure,  Steven Tyler [or rms]  can act that way, but you're not in his league, don't get uppity,').


问:
How would you design a programming language?
If you were to design a programming language, how would you do it? What features would you put in? What would you leave out? Statically or dynamically typed? Strongly or weakly typed? Compiled or interpreted? Justify your answers.</p>

答:
Before designing a programming language, I would find a good answer to the question: why do we need yet another programming language? Rosetta Code at the time of this writing lists 344 languages. If none of those met my needs, the specifics of why they didn't would determine the starting point (languages that come the closest) and what would be added to it.

If I won the lottery and for some reason had nothing better to do, I would start with Liskell and make it a full-fledged language as opposed to a GHC front-end, then make FFI easier (and automated) so I could use any C/C++ library.

ContentLicense: CC BY-SA 2.5


问:
How to design website workflow?
I have been thinking about this for really long time without reaching an optimum answer.

First of all, I'm a medical doctor who loves programming but never really studied it, except for home learning and lots of years of playing around with code in my free time.

Currently I'm trying to build a small project to manage my clinic, to do that I started by created a list of options I want to be able to do.

Example:

active patient record.

authentication with different roles (eg. patient,nurse,dr)

appointment schedule (include calendar to schedual vacinations/surgeries etc with a reminder)

allow doctor to create his own plugins.

dashboard for doctor to view his statistics

Then I started with codeigniter/mysql/php/jquery and started coding.

My steps during development:-

1st database.

I started by creating all my tables that I will need.

Created all my models to handle these tables (1 master model that handle basic read/write/update/verify while also considering my table relations

After that I start to code my views and controllers. I first created view HTML, then create controller that will handle this view, and started coding functions to make the view interactions work.

Example when coding the appointment view(controller booking.php):

created this layout and made table td's clickable,
when user click : jquery get (booking/add_patient_form) and pop it up

when user save  : post to booking/save -it save appointment then reload index() function

etc.. and I continued same steps of creating view then its controller -that contain all the logic this view needed - to accomplish whole project.

At the end I had all my target functions working fine, but since there was no PLAN from beginning and as the whole project was punch of brain storming and debugging with no what so ever plan, after I went so far in this project i find my self stuck with maintainability and flexibility! and unable to link them together.

I have feeling that every page on website is completely isolated from other and I can't even recall how each page is loaded and what functions are inside without peeking!

Is there anyway I can recover this and get a design out?

答:
I would advise you to keep the database structure and generate new PHP code with PHP Generator for MySQL created by the company SQL Maestro. It really worked for me. I use it a lot and I am really happy with it, especially the possibility to tweak the PHP code to my own needs. Furthermore, they incorporate your requested new features in their updates and have nice tutorials how to tweak the code. To better understand have a look at this demo project.

On their website the following product description is given:

PHP Generator for MySQL is a MySQL GUI frontend that allows you to generate high-quality PHP scripts for the selected tables, views and queries for the further working with these objects through the web. Key features include:

Data management: add, edit, delete and copy records

Customization of the HTML appearance

Filtering and sorting abilities

Data protection with a lot of security settings

Master-detail presentations

Event-driven content management

Data export to PDF, XML, CVS, Excel and Word

PHP Generator for MySQL produces clear and easy to understand code that can be used as is or modified in any way you need.

Save the huge costs of hiring a programmer, learning any programming language, or buying an expensive software - all the code is automatically generated for you!

OwnerDisplayName: Momen M El Zalabany

ContentLicense: CC BY-SA 3.0

Title: How to design website workflow?


问:
Is Groovy going away?
I am sure this question has been asked many times. However, I like to ask it again with the intention of what is the future of these languages.

I was first introduced to Groovy and really liked it. I felt the syntax was simpler and it was much closer to Java and I was able to quickly learn Grails.

Then there was Scala, and the web frame work Lift. I am still learning Scala and I find the syntax very difficult at times.

However, I still wonder what is the future of Groovy. When the author of Groovy says he would have never created groovy if he knew about Scala, then it makes me wonder if there is a future at all. Of course Groovy has came a long way and Grails is used today by many large companies.

If one was to look at Grails vs Lift today, then Grails would be clear winner. More companies are using it.  But given everything I have said so far, I am interested to know if one should invest in Groovy? Is Groovy going away and Scala the better choice? If the CEO of BMW says he drives a Mercedes then one would wonder why shouldn't we all drive Mercedes too, right?

(I understand if this question is really broad and might be closed. I hope to make it an open Wiki for others though.)

答:
Not to knock the general excellence of Groovy or indeed Ruby, but, over 90% of web traffic is to sites written in PHP or some Java framwork.

I don't know where you got the "Grails is used by many large companies" this is pretty much like saying "all the fortune 500 companies use Python" which is actually true, but, they do not use python for anything business critical.

They are right not to use Grails, Rails etc. they are great for small neat sites, but, they do not scale well. Also most large businesses have intricately inter-connected systems, and the major challenge when building web applications revolve around how to connect to all the other systems which provide or consume your data -- coding by convention just does not work in this space.

Groovy the language's main competitor is actually JPython which operates in the sames space (Scripting on a JVM) and is used for the same sort of things (Automated tests, automated builds etc,).

Title: Is Groovy going away?


问:
terms for the html/css/javascript model?
Are there any words for the design model implemented by HTML + CSS + JavaScript, either for that specific set of technologies or any abstract pattern that they follow?</p>

答:
This particular set - with Flash optionally thrown in - is generally called browser-side or client-side (although the latter can be used in different contexts too).

The whole application is implemented browser-side. The webserver just provides static content.

In case you add dynamically generated data from the server - static HTML, CSS, JS and dynamic data in JSON or XML - it's called AJAX.


问:
Is the 80 character limit still relevant in times of widescreen monitors?
on a widescreen monitor one can easily see more than 80 characters at a time, without scrollbars. even linus torvalds sees the 80 character limit as outdated.

so, is the 80 character limit still relevant in times of widescreen monitors?

答:
There are several reasons to still adhere to an 80 character limit (or, a 74 character limit is even better; it allows for the code to remain fewer than 80 columns even when diff markers and email quoting is added, if you do code review on mailing lists).

Even in the era of widescreen monitors, I like to have several windows open side by side, showing different parts of the code. For instance, I usually have a web browser and email open on one screen, and two files and a terminal open side by side on a second monitor. If you have lines that run over 80 columns, you need to deal with the editor wrapping the lines (which is ugly and makes the code harder to navigate around), or widen you windows such that you can't fit as many on screen at once.

Even if you don't usually edit this way, if you ever use a side-by-side diff tool, you will appreciate files with reasonable line lengths which will make your diff easier to view.

There's also an issue of code density. I like to have a lot of context when reading code. It is much, much quicker to glance up and down a window than it is to scroll. If you have very long lines, you also tend to have lines that vary in length a lot, leading to a lot of wasted screen real estate and being able to fit less code on screen at a given time overall.

And finally, if you have very long lines, then that generally means that you have very complicated lines, deep indendation, or that you have very long identifiers. All of these can be a problem. Complicated lines are probably doing too much; if you can break it down into several simpler lines, you probably should. Deep indentation means that you're probably nesting too many loops and conditionals, which can make your code flow confusing; considering refactoring into several functions. And if your identifiers are too long, it can make reading your code very difficult. People generally recognize words as individual units; they don't read every character one by one, but look at the overall shape of the word. Long identifiers are harder to distinguish this way, and usually if they are that long, they contain redundant or repetitive information.

Now, while it's still good practice to keep code below 80 columns, this isn't one of those rules that needs to be followed religiously, contorting yourself to make some line fit when it just doesn't. I suggest that you try to keep all of your code under 80 columns, but when it just doesn't fit, don't worry about it too much.


问:
Can Objective C categories serve the same purpose as Traits do in Scala?
The statement of the question seems little abstract to me, so please read the details below.

Since the time when C++ was the first choice Object Oriented Language for almost anything, we had a big problem of Multiple inheritance in C++ when two different implementations of same function declared or defined in a (abstract or concrete)parent class of the two, come to a common child class and create ambiguity, popularly known as the Diamond problem.

C++ gave a solution : the "virtual" keyword, to be used while specifying the parent class(es) so that only one copy goes to the final child class being decided at runtime instead of compile time based on certain rules.

Java tried to solve this by providing single inheritance and avoiding multiple inheritance completely.

But then it lacked a feature where a class behaviour could be influenced by a bit and that may change in future or more behaviour may be added to it and we needed a way to encapsulate behaviour, then came the construct "interface" which had nothing but method declarations which each implementing class had to implement in their own way.

Protocols in Objective C are more or less the same thing.

However this approach has a major drawback, and this is where my question comes into picture.

The drawback is, if a class has many subclasses implementing the same interface in the same way. The same code has to be written everywhere in each class.

If it was all the classes, then the implementation could have been there in the parent class which gives the implementation.

At max what can be done is to introduce a class with the implementation of the common method in between the current parent class and make all those classes inherit from it.

But this can lead to lot of bugs if not done properly in a complex project.

Scala provides Traits which not only serve as interfaces but can add full blown implementations for few of them that can be mixed with some classes that require it and removed when not.

I haven't seen the syntax but I have heard that Ruby solves the same problem using something called as mixins.

In case of Objective C, we have protocols but they have the same limitations as Java interfaces.

So my question is, If I create a category of a class and  import it in any subclass of that class, Will the subclass get all those implementation methods? Also if I remove it, will it be synonymous to removing the trait inclusion declaration for a class?

I might be wrong in any of my assumptions above, I am newbie when it comes to OOP design (and just got interested in FP).

I would also appreciate any better solutions than this one.

答:
Importing (#import ...) an Objective-C category adds the methods defined in that category to all instances of the class on which the category was defined. Other than with traits which can be mixed into classes selectively a category extends the class on which it was defined once and for all.

Also you can not create a standalone category and mix that into several different classes. A category is an extension for a specific class, similar as if you would add the methods to the class itself.

Traits are like java interfaces but with implementation. Wether a trait can be mixed into a class depends not on the classes name but on the methods the class provides. If a class has the methods a trait needs, the trait can be mixed into that class.


问:
How to code in a more functional style in Java?
I code Java for at least 5 years now and I really appreciate how the language works. When looking at new JVM languages (e.g. Scala, Clojure) there is a trend to more functional ways to code and this way has some major advantages.

Anyway, are there patterns to achieve a more functional style even when using Java or other pure OOP? And does this make sense in Java?

答:
A good start is Neal fords: functional thinking.

You should then explore libraries like:
Google guava , it's collections for essential abstractions like, function, predicate, map and filter operations.(google for functional programming with google collections, there are a couple of good blogposts)

There are couple of blogs about FP in java I read apocalisp.wordpress.com and I didn't regret it.

You may also explore functionaljava.org for more useful functional constructs like monoids.

Learning Haskell, Scala or Clojure is also a good idea but of course a bit more involved.

Good luck!


问:
Question about the use of the word 'porting' in programming
I'm currently in the process of modifying a C++ code that was written for UNIX system so that it works by compiling from Visual Studio. I had to change some built-in functions' names and I had to change the way dynamic arrays are defined.

My question is, can I say that I'm 'porting' this code from UNIX to Windows/Visual Studio or is 'porting' used only when changing from one programming language to another (porting from C++ to Java)?

答: Porting is becoming more and more popular in game development, as the publishers want to cover as many platforms as possible (PC, Xbox, Playstation, etc.). As mentioned, porting means converting the original program so that it works in a completely different system. Generally the game makers convert console games to PC.</p>


问:
Branch vs decision coverage question
ISTQB does not distinct between these (it reads "Branch/decision coverage") but some sources do say it is different.
I would have two question. The essential one is about the difference. And the other one - does this whole concept belongs under the unit testing? Or white box testing?
Thanks

From the ISTQB:

branch coverage is closely related to decision coverage and at 100%
  coverage they give exactly the same results. Decision coverage
  measures the coverage of conditional branches; branch coverage
  measures the coverage of both conditional and unconditional branches.
  The Syllabus uses decision coverage, as it is the source of the
  branches. Some coverage measurement tools may talk about branch
  coverage when they actually mean decision coverage. (c) ISTQB
  foundation book.

答:
If you think about your program as a big directed graph with a start node going to one or more end nodes. Each statement in your program is a node on the graph, branches or decisions are edges between nodes.

Full statement coverage is when you visit every node in the graph at least once,
full branch/decision coverage is when you traverse every edge in the graph at least once (and I think they are the same thing).

Neither of these is necessarily the same as Full path coverage, when you traverse every path from the start node to every end node.

As with any terminology there is no guarantee that everyone means exactly the same thing by the same term. Wikipedia seems to take branch coverage to mean modified decision coverage but there are plenty of other sources, as you note, that say they are the same. What we can say more authoritatively is that statement coverage is not the same as branch coverage, and neither are the same as path coverage.

If you need to use these terms then your best bet is to define what you mean by them before you use them.

For point 2. Coverage metrics can be used on any form of testing, it is certainly fairly common to use it on unit tests and on automated system/integration tests

Title: Branch vs decision coverage question


问:
I've been told that Exceptions should only be used in exceptional cases. How do I know if my case is exceptional?
My specific case here is that the user can pass in a string into the application, the application parses it and assigns it to structured objects.  Sometimes the user may type in something invalid.  For example, their input may describe a person but they may say their age is "apple".  Correct behavior in that case is roll back the transaction and to tell the user an error occurred and they'll have to try again.  There may be a requirement to report on every error we can find in the input, not just the first.

In this case, I argued we should throw an exception.  He disagreed, saying, "Exceptions should be exceptional:  It's expected that the user may input invalid data, so this isn't an exceptional case"  I didn't really know how to argue that point, because by definition of the word, he seems to be right.

But, it's my understanding that this is why Exceptions were invented in the first place.  It used to be you had to inspect the result to see if an error occurred.  If you failed to check, bad things could happen without you noticing.

Without exceptions every level of the stack needs to check the result of the methods they call and if a programmer forgets to check in one of these levels, the code could accidentally proceed and save invalid data (for example).  Seems more error prone that way.

Anyway, feel free to correct anything I've said here.  My main question is if someone says Exceptions should be exceptional, how do I know if my case is exceptional?

答:
I've never been a great fan of the advice that you should only throw exceptions in cases that are exceptional, partly because it doesn't say anything (it's like saying that you should only eat food that is edible), but also because it is very subjective, and it's often not clear what constitutes an exceptional case and what doesn't.

However, there are good reasons for this advice: throwing and catching exceptions is slow, and if you are running your code in the debugger in Visual Studio with it set to notify you whenever an exception is thrown, you can end up being spammed by dozens if not hundreds of messages long before you get to the problem.

So as a general rule, if:

your code is bug free, and

the services on which it depends are all available, and

your user is using your program in the way that it was intended to be used (even if some of the input they provide is invalid)

then your code should never throw an exception, even one that is caught later. To trap invalid data, you can use validators at the UI level or code such as Int32.TryParse() in the presentation layer.

For anything else, you should stick to the principle that an exception means that your method can not do what its name says that it does. In general it's not a good idea to use return codes to indicate failure (unless your method name clearly indicates that it does so, e.g. TryParse()) for two reasons. First, the default response to an error code is to ignore the error condition and carry on regardless; second, you can all too easily end up with some methods using return codes and other methods using exceptions, and forgetting which is which. I have even seen codebases where two different interchangeable implementations of the same interface take different approaches here.


答:
One can port software between operating systems.  One can port software between processor architectures.  One may need to perform some of the activities I'd normally associate with "porting" when dealing with major platform changes (Apple's PPC -> x86 switch, or Windows XP -> Windows Vista/7/8).  I wouldn't consider switching programming languages to be "porting."  More like completely rewriting.

I've ported software from Linux to Windows and vice-versa.  I've ported software from SPARC to x86 (I just love dealing with endian issues)  And from 32-bit to 64-bit.  These days I'm programming in Java... I'm not sure if the word "porting" has much meaning in Javaland, perhaps between major JVM versions....

Title: Question about the use of the word 'porting' in programming

Body:
I'm currently in the process of modifying a C++ code that was written for UNIX system so that it works by compiling from Visual Studio. I had to change some built-in functions' names and I had to change the way dynamic arrays are defined.

My question is, can I say that I'm 'porting' this code from UNIX to Windows/Visual Studio or is 'porting' used only when changing from one programming language to another (porting from C++ to Java)?


问:
Matching up articles with similar ones
I am creating a site where people can write on a niche topic. It is almost like a blog, however the area as I mentioned is a small niche with (hopefully) passionate users.

I want a functionality where once someone posts his article. People with similar experience can be notified, so that they can read about. Now my question is - how to determine similar articles? I know that tagging is a way - just like here in stackexchange and I will be implementing it. But suppose people do not tag, or tag incorrectly, the whole user experience will be hard to indulge in.

Does anyone have any pointers on how to match up articles other than the tagging method?

答:
I am currently undertaking a similar (although more generic) project with my lab. As such, I want to warn you that this feature is a rabbit hole that can get very complicated very quickly. The first thing you need to do is think about your users and your goals and decide what's "good enough" or you will spend a lot of time developing a feature that, in the grand scheme of your site, might not be that important.

Basically you want some sort of information retrieval system. Think a mini-Google but not nearly as complex. First you need to decide how you will define similarity between articles (a metric). This will be handled in your preprocessing. Generally your actually comparison will be the same no matter what your metric (typically cossine similarity).

Defining a Metric

First, you need to decide what makes articles similar. There are two main approaches: looking for similarities in article topics or looking for similarities in article text. Topics will give better results but text is easier to implement.

Similarity by Topic

As mentioned several times, the easiest way to implement this system is allowing specify topics through author-specified tags. You would then search for articles with large overlaps in tags. If the tags are numerous and fine grained enough then this should give the best results.

The disadvantage is that you need to put a lot of thought into what the tags are to ensure you have coverage, clarity, and a lack of redundancy. If you take the Stack Exchange approach of letting users create their own tags then you can increase coverage but you need to moderate the tags to maintain the clarity/lack of redundancy. However, the greatest drawback of this approach is that you are trusting users to appropriately tag their posts. SE gets around this problem by letting other users edit and make suggestions for the tags.

You can get even better results if you tag topics at the sentence or paragraph level. It gives a better representation of which topics are more important in an article but it's more work. As the tagging scope gets smaller, the complexity of this task becomes exponentially more difficult.

What about an automated solution to take the work load off the users? Automatic Topic Identification is something that has been studied a lot. I'm not an expert at it but I suggest you read a few papers and decide if you feel these solutions are mature enough to give reliable results. My concern with this approach is that since you admit your domain is niche you might have a hard time finding an out-of-the-box solution and will need to implement the topic identifier yourself. At that point you might as well just do text-based similarity because it will be much easier and out-of-the-box solutions exist.

Similarity by Text

In this approach instead of comparing topic tags, you compare the actual words in the article. The advantage is that the preprocessing is much easier to accomplish. The disadvantage is that it assumes that similar text means a similar topic, which is not always the case.

Making it Work

In general, whichever metric you choose you will end up with a vector representing your articles. Maybe the vector is of word frequencies or of topic tags. You now need to compare the vectors for your articles to see which are similar.

The Stanford Natural Language Processing Course offered on coursera.com is a good introduction to Information Retrieval (specifically the Week 7 lectures). Keep in mind that the solutions presented in those lectures are relatively basic, but it's a good start.

I would heavily suggest trying to find an out-of-the-box implementation here. Failing that, using a toolkit like Apache Lucene will greatly simplify your development.

Now you need to test out a bunch of term weighting algorithms and see which one gives the best results for your data. TREC is a competition to find better and better weighting algorithms. Check the proceedings on their website to find discussions of newer, more accurate weighting algorithms.

Title: Matching up articles with similar ones


问:
should I be putting database connections into a class library?
This might be a stupid question but I've never created a class library before

The reason I don't want to be connecting to a database through the class library is error handling.. should I just leave the errors to throw back to whatever code is using the class library? should I handle it there? or should I just leave it completely and take the whole database object out of the library, creating it seperately/ copying and pasting every time I want to use it.

This is a small project with only 12 classes, all under 200 lines and is only going to be used on in house company applications. I'm probably going to be the only one using it to develop with unless I leave and someone needs to make changes to the applications.

It's c# if that makes even the slightest difference?

答:
No, you shouldn't.

You should pass in connection strings as a dependency, or use ConfigurationManager to pick them up from the application configuration.

Hard coding them means that you can't change them without recompiling the libraries.

The reason I don't want to be connecting to a database through the class library is error handling

False logic there. You should handle database issues in that data access layer (which can be in a class library) - other logical and business issues should be handled in the business logic layer (which can also be its own class library).

Exceptions that are not handled bubble up.

OwnerDisplayName: Alex


答:
Normally one puts everything related to data access in a data access layer (DAL) which would be a separate DLL-file. Creating this class library is pretty straight forward. Just remember to add a reference to your newly created project in you main project.

Whether or not you deal with exceptions in the DAL or you let the business logic layer deal with it is more a matter of taste. I personally prefer dealing with return codes that indicate success or failure rather than surrounding all calls to the DAL with try/catch.

Keeping data access in a different class library will make your code more manageable, even if you decide to scale up the project. In a deployed product, updates to the logic of the DAL can be as easy as swapping a DLL file as opposed to update the whole program.

Title: should I be putting database connections into a class library?

Body:
This might be a stupid question but I've never created a class library before

The reason I don't want to be connecting to a database through the class library is error handling.. should I just leave the errors to throw back to whatever code is using the class library? should I handle it there? or should I just leave it completely and take the whole database object out of the library, creating it seperately/ copying and pasting every time I want to use it.

This is a small project with only 12 classes, all under 200 lines and is only going to be used on in house company applications. I'm probably going to be the only one using it to develop with unless I leave and someone needs to make changes to the applications.

It's c# if that makes even the slightest difference?


问:
Auto-completion or Suggest
How does Google or amazon implement the auto-suggestion at their search box. I am looking for the most used algorithm with technology stack.

PS: I have searched over the net and found this and this and many many more. But I am more interested in not what they do but how they do it. NoSQL database to store the phases? or is it sorted or hashed according to keyword's? So to rephrase the question: Given the list of different searches ignoring personalization, geographic-location etc, How do they store, manage and suggest it so well.

答: I believe Google still uses BigTable for their web indexing, and thus probably the same for their auto complete. But they keep on redeveloping their solutions, as their data-set obviously increases and a certain solution might not be working at a certain point of time for them anymore.</p>

Title: Auto-completion or Suggest


问:
Class inheritance and extra parameters
Im trying to create an SMS gateway .. I have a request coming in from a client (web form or API or database record) that I need to process and forward on to a 3rd Party API - or SMS provider. So that things would be simpler going forward I decided to create an interface that each provider implementation would implement :

```<code>interface SMSProvider
  public method sendSMS(sendTo,message)
  public method sendWakeup(sendTo)
</code>```

I thought this would be my best way forward because then I wouldn't have to change my code when sending to a different provider - i knew that when i create my provider i just call the method to perform the function with the normal parameters and everything is good ... Well until I have a new provider that requires new parameters

```<code>new provider requires
  - sendTo
  - message
  - sendFrom
  - validityPeriod
</code>```

So now what do i do ? how can i now use my interface ? when the new provider needs extra parameters ?

答:
The usual practice in this case is to wrap arguments of interface methods into abstract classes and have implementing classes instantiate certain variation of the abstraction. So,

```<code>interface SMSProvider
public method sendSMS(SMSMessage)
public method sendWakeup(WakeupMessage)

class SMSProvider1
public method sendSMS(Provider1SpecificSMSMessage)
public method sendWakeup(Provider1SpecificWakeupMessage)

class SMSProvider2
public method sendSMS(Provider2SpecificSMSMessage)
public method sendWakeup(Provider2SpecificWakeupMessage)

abstract class SMSMessage
string sendTo
string message

class Provider1SpecificSMSMessage :: SMSMessage
/*
fields from base class plus customizations
*/

class Provider2SpecificSMSMessage :: SMSMessage
/*
fields from base class plus customizations
*/
</code>```

[Sorry, not sure what language you're dealing with]

Title: Class inheritance and extra parameters

Body:
The usual practice in this case is to wrap arguments of interface methods into abstract classes and have implementing classes instantiate certain variation of the abstraction. So,

interface SMSProvider
public method sendSMS(SMSMessage)
public method sendWakeup(WakeupMessage)

class SMSProvider1
public method sendSMS(Provider1SpecificSMSMessage)
public method sendWakeup(Provider1SpecificWakeupMessage)

class SMSProvider2
public method sendSMS(Provider2SpecificSMSMessage)
public method sendWakeup(Provider2SpecificWakeupMessage)

abstract class SMSMessage
string sendTo
string message

class Provider1SpecificSMSMessage :: SMSMessage
/*
fields from base class plus customizations
*/

class Provider2SpecificSMSMessage :: SMSMessage
/*
fields from base class plus customizations
*/

[Sorry, not sure what language you're dealing with]


答:
Here's the problem in a nutshell:

```<code>if ((test1() || test2()) {
    invoke_some_latent_bug_only_if_test1_is_false;
}
else {
    do_something_benign;
}
</code>```

Suppose you have two test cases:

test1() evaluates to true, and

Both test1() and test2() evaluate to false.

Some code coverage tools will yield 100% coverage because these two test cases result in the execution of every statement. The problem is that every path has not been tested. This code needs three test cases, one more for the case where test1() evaluates to false but test2() evaluates to true.

In this hypothetical example, that third critical test case would expose that latent bug. If you fail to provide that third case and use a coverage tool based solely on statement executions you will get a false sense that testing is complete.

Title: Branch vs decision coverage question

Body:
ISTQB does not distinct between these (it reads "Branch/decision coverage") but some sources do say it is different.
I would have two question. The essential one is about the difference. And the other one - does this whole concept belongs under the unit testing? Or white box testing?
Thanks

From the ISTQB:

branch coverage is closely related to decision coverage and at 100%
  coverage they give exactly the same results. Decision coverage
  measures the coverage of conditional branches; branch coverage
  measures the coverage of both conditional and unconditional branches.
  The Syllabus uses decision coverage, as it is the source of the
  branches. Some coverage measurement tools may talk about branch
  coverage when they actually mean decision coverage. (c) ISTQB
  foundation book.

Body:
Here's the problem in a nutshell:

if ((test1() || test2()) {
    invoke_some_latent_bug_only_if_test1_is_false;
}
else {
    do_something_benign;
}

Suppose you have two test cases:

test1() evaluates to true, and

Both test1() and test2() evaluate to false.

Some code coverage tools will yield 100% coverage because these two test cases result in the execution of every statement. The problem is that every path has not been tested. This code needs three test cases, one more for the case where test1() evaluates to false but test2() evaluates to true.

In this hypothetical example, that third critical test case would expose that latent bug. If you fail to provide that third case and use a coverage tool based solely on statement executions you will get a false sense that testing is complete.


问:
How do we make unit tests run fast?
We have reached the point in our project where we have almost a thousand tests and people have stopped bothering with running them before doing a check in because it takes so long. At best they run the tests that are relevant to the piece of code that they changed and at worst they simply check it in without testing.

I believe this problem is due to the fact that the solution has grown to 120 projects (we usually do much smaller projects and this is only the second time we do TDD properly) and the build + test time has grown to about two-three minutes on the lesser machines.

How do we lower the run time of the tests? Are there techniques? Faking more? Faking less? Maybe the bigger integration tests shouldn't run automatically when running all the tests?

Edit: as a response to several of the answers, we already use CI and a build server, this is how i know the tests fail. The problem (actually a symptom) is we keep getting messages about failed builds. Running partial tests is something that most people do but not all. and regarding the tests, they are actually pretty well made, they use fakes for everything and there is no IO at all.

答:
Train your developers on Personal Software Process (PSP) helping them to understand and improve their performance by using more discipline. Writing code has nothing to do with slamming your fingers on a keyboard and afterwards press a compile and check in button.

PSP used to be very popular in the past when compiling code was a process which took a lot of time (hours/days on a mainframe so everybody had to share the compiler). But when personal workstations became more powerful, we all came to accept the process:

type some code without thinking

hit build/compile

fix your syntax to make it compile

run tests to see if what you wrote actually makes sense

If you think before you type, and then after you typed, review what you wrote, you can reduce the number of errors before you run a build and test suite. Learn not to press build 50 times a day, but maybe once or twice, then it matters less that your build and testing time takes a few minutes more.

Title: How do we make unit tests run fast?


答:
One possible way: split your solution. If a solution has 100 projects, then it's quite unmanageable. Just because two projects (say A and B) use some common code from another project (say Lib) doesn't mean they have to be in the same solution.

Instead, you can create solution A with projects A and Lib and also solution B with projects B and Lib.

Title: How do we make unit tests run fast?

Body:
We have reached the point in our project where we have almost a thousand tests and people have stopped bothering with running them before doing a check in because it takes so long. At best they run the tests that are relevant to the piece of code that they changed and at worst they simply check it in without testing.

I believe this problem is due to the fact that the solution has grown to 120 projects (we usually do much smaller projects and this is only the second time we do TDD properly) and the build + test time has grown to about two-three minutes on the lesser machines.

How do we lower the run time of the tests? Are there techniques? Faking more? Faking less? Maybe the bigger integration tests shouldn't run automatically when running all the tests?

Edit: as a response to several of the answers, we already use CI and a build server, this is how i know the tests fail. The problem (actually a symptom) is we keep getting messages about failed builds. Running partial tests is something that most people do but not all. and regarding the tests, they are actually pretty well made, they use fakes for everything and there is no IO at all.


答:
The majority of Unit Tests should take under 10 milliseconds each or so. Having 'almost a thousand tests' is nothing and should take maybe a few seconds to run.

If they're not, then you should stop writing highly coupled integration tests (unless that's what the code needs) and start writing good unit tests (starting with well decoupled code and proper usage of fakes/mocks/stubs/etc). That coupling will impact test quality and the time it takes to write them too - so it's not just a matter of reducing test run time.

Title: How do we make unit tests run fast?


答:
A possible solution would be to move the testing portion from the development machines to a continuous integration setup (Jenkins for example) using version control software of some flavor (git, svn, etc...).

When new code has to be written the given developer will create a branch for whatever they are doing in the repository. All work will be done in this branch and they can commit their changes to the branch at any time without messing up the main line of code.

When the given feature, bug fix, or whatever else they are working on has been completed that branch can be merged back into the trunk (or however you prefer to do it) where all unit tests are run. If a test fails the merge is rejected and the developer is notified so they can fix the errors.

You can also have your CI server run the unit tests on each feature branch as commits are made. This way the developer can make some changes, commit the code, and let the server run the tests in the background while they continue to work on additional changes or other projects.

A great guide to one way of doing such a setup can be found here (git specific but should work for other version control systems): http://nvie.com/posts/a-successful-git-branching-model/

Title: How do we make unit tests run fast?


答:
I am in a similar situation. I have unit tests which test communication with the server. They are testing the behavior with timeouts, cancelling connections etc. The whole set of tests runs 7 minutes.

7 minutes is a relatively short time but it's not something you will do before every commit.

We also have a set of automated UI tests, their run time is 2 hours. It's not something you want to run every day on your computer.

So, what to do?

Changing the tests is usually not very effective.

Run only the relevant tests before your commit.

Run all of your tests every day (or several times a day) on a build server. This will also give you the possibility to generate nice code coverage & code analysis reports.

The important thing is: all of your tests should be run often because it's important to find the bugs. However, it's not absolutely necessary to find them before the commits.

Title: How do we make unit tests run fast?


答:
There are several approaches I have used to solve similar issue:

Check execution time, and find all most slowest tests and then analyze why they take so much time to execute.

You have 100   projects, may be you do not need to build and test them every time? Could you run all unittest only at a night builds? Create several 'fast' build configurations for daily use. CI server will perform only limited set of unittests projects related to 'hot' parts of your current development process.

Mock and isolate everything you could, avoid disk/network I/O whenever it's possible

When it isn't possible to isolate such operations, may be you have integration tests? May be you could schedule integration tests to night builds only?

Check all occasional singletons, that keep references to instances/resources and that consume memory, this could leads to performance degradation while running all tests.

In addition you could use following tools to make both your life easy and tests run faster

Gated commit some CI servers could be configured to perform build and test before commiting code to source repository. If someone commits code without running all tests beforehand, that contains also failed tests, it will be rejected and returned back to author.

Configure CI server to execute tests in parallel: using several machines or processes. Examples are pnunit and CI configuration with several nodes.

Continuous testing plug-in for developers, that will automaticaly run all test during writing code.

Title: How do we make unit tests run fast?


问:
Determining which decorator classes are available via reflection
I'm creating a pizza place application where employees will be able to create orders for customers(pizza and any number of toppings). This is for a school project but the requirements have nothing to do with this question.

On the GUI I have a number of checkboxes that the employee will use to determine which toppings the pizza should have. I want to use the decorator pattern for this.

This is what I want to do(just not sure if its a good idea):

I want to put all of my decorators in a separate namespace, and then using reflection grab all of the decorator names out of that name space and use them to build the checkbox list. The reason for doing this is because if more toppings are added later I think it would be beneficial to just be able to add assemblies (topping decorators) without having to recompile/re-distribute the entire application.

Thoughts?

(I just learned reflection and I have a hammer and am just trying to pound everything in that even remotely looks lilke a nail)

答:
It's not a bad approach in general - if there's some common interface like "IPizzaTopping" and your new assemblies contain items of that interface then you can pull out all of the things in an assembly with that type.

Saying that, it's complete overkill for something like pizza toppings (where an xml config could probably suffice) but I have seen it used to great effect with plugin type architectures.


问:
Purpose of Base Address?
What's the purpose of a base address in an executable?

For example, in Microsoft Visual C++'s linker, you can set a base address, or use the default of 0x1000000. But with virtual memory, why would a base address be needed?

Why would you not just link it to 0x0 and put the initialization routine (mainCRTStartup on Windows) there which would make it so writing to NULL (0x0) would just overwrite the startup routine (a method that will never be called again). Plus, you could just set the code's pages to execute only on an x86 processor so writing will cause an exception.

答:
Base addresses are needed to compute the virtual addresses of objects in the file after it has been loaded into virtual memory. Remember that the linker may have to link many PE files, and each one may request to be loaded at 0x0- this means that the PE file will have to cope with being located in different places in virtual memory.

The base address is used to make the other addresses relative- so if you have a vtable, you load the address 0x1000FF00, say. Then, when the dynamic linker rebases the executable because there was already something there, it knows how to modify this address to point to the new location.

Title: Purpose of Base Address?


答:
The question is not so much whether or not you should use reflection to build the list of checkboxes from the set of subclasses you have defined. Once you have made that choice, and want to keep the GUI up-to-date without recompiling or maintaining the possible toppings in two different places (always a bad sign), there is little else you can do to enumerate classes (it would be different if you were enumerating instances of sibling classes, but I'm assuming there isn't actually a persistent repository of Cheese, Tomato or Onion objects over which you could iterate).

The question should rather be: is representing toppings as classes the right idea, or is it overkill? As long as the only thing characteristic of a topping is what it makes the decorated pizza looks like, they could very well be parametrized instances of the same class. Having multiple subclasses is usually a good idea when one ore more behaviours systematically differ between them. For instance, the frameworks on which environments like Eclipse or NetBeans are built allow contributors to write extremely powerful plug-ins that nevertheless integrate into an existing installation, which involves implementing dozens of different behaviours. Not surprisingly, the frameworks themselves are heavily dependent on reflection to achieve the amazing flexibility they offer. But your problem, I think, is not so much a case of over-eager reflection than a case of over-eager inheritance.

Title: Determining which decorator classes are available via reflection

Body:
I'm creating a pizza place application where employees will be able to create orders for customers(pizza and any number of toppings). This is for a school project but the requirements have nothing to do with this question.

On the GUI I have a number of checkboxes that the employee will use to determine which toppings the pizza should have. I want to use the decorator pattern for this.

This is what I want to do(just not sure if its a good idea):

I want to put all of my decorators in a separate namespace, and then using reflection grab all of the decorator names out of that name space and use them to build the checkbox list. The reason for doing this is because if more toppings are added later I think it would be beneficial to just be able to add assemblies (topping decorators) without having to recompile/re-distribute the entire application.

Thoughts?

(I just learned reflection and I have a hammer and am just trying to pound everything in that even remotely looks lilke a nail)


答:
Adding to what others have already said here, in Functional Programming there is a drive to separate side-effect producing / state changing code from functionally pure code and to make the separation explicit. This is achieved in e.g. Haskell through use of the IO and State Monads and in Clojure through refs.

In OOP state and state change are encapsulated in objects, so unless you go the immutable object route, this will likely be a bit more difficult to do.

Something that might help is to follow the Command/Query Separation Pinciple, which states that an operation should either be a command and cause side-effects, but not return anything, or it should be a query with a return value, causing no side-effects. Following this principle could help to get one into a more functional mindset, so far as managing side-effects is concerned.

EDIT

I don't know why this was initially down-voted; There's an article by John Carmack on Functional Programming in C++ which starts out similar what I've said above (sans the C/Q separation part) -- this is easily applicable to Java too.

Title: How to code in a more functional style in Java?

Body:
I code Java for at least 5 years now and I really appreciate how the language works. When looking at new JVM languages (e.g. Scala, Clojure) there is a trend to more functional ways to code and this way has some major advantages.

Anyway, are there patterns to achieve a more functional style even when using Java or other pure OOP? And does this make sense in Java?


答:
Traditionally executables get mapped at their desired base address, if that's not in use yet. You can't map at 0, since the lowest part of the address space is reserved (leads to crashes on null pointer dereferencing, instead of accessing memory you didn't intend to acceess).

Since you only load a single .exe file into a process, they don't need to use a unique base address. So most .exe files keep the default value 0x400000. They often lack a relocation table, and thus must be loaded at that address.

For dlls things are a bit more complicated, since their target address can be in use already. In that case they'll get mapped at another address, and a relocation table is used to patch parts of its code that now need to point to other addresses. This fixup costs both CPU time and memory (executables are mapped as copy-on-write, and the fixup means your application gets a unique copy of the dll). So base addresses for dlls are typically chosen to avoid overlaps and thus relocation.

Nowadays things are different. RAM is much cheaper, so the cost of relocation isn't that important anymore. On the other hand security is very important now. So we use a process called ASLR where executables are mapped at unguessable addresses. This makes the base address the executable specifies rather meaningless.

Thus executables being able to choose their own base address is a performance optimization that was useful on slow computers with little RAM but isn't useful on modern systems anymore since MS decided to trade a bit of performance for increased security.

Title: Purpose of Base Address?

Body:
What's the purpose of a base address in an executable?

For example, in Microsoft Visual C++'s linker, you can set a base address, or use the default of 0x1000000. But with virtual memory, why would a base address be needed?

Why would you not just link it to 0x0 and put the initialization routine (mainCRTStartup on Windows) there which would make it so writing to NULL (0x0) would just overwrite the startup routine (a method that will never be called again). Plus, you could just set the code's pages to execute only on an x86 processor so writing will cause an exception.


问:
Scalability: How does splitting a database table work on different replicated SQL Servers?
I would like to know more about the general concepts behind dividing data of a database into different servers. For example, suppose I have a SQL Server database which has a massive table. Assume one single server cannot handle the amount of data in this table. I would like to break that table down and split its contents among different servers with an identical database (replicated).

Now, suppose I have a single SQL (ADO) connection to any one of these servers, and choose to select records from this particular table. Since the data is in separate databases on separate servers, I need to gather the records from all the various servers and combine them into one.

I'm sure there's standard ways of accommodating for this, and I'm willing to go another route than a direct SQL Server connection (I plan to wrap it in my own HTTP Server API anyway) but I'm still going to use SQL Server as the actual engine. What is the most standard practice and where can I learn more about it?

答:
I think ultimately what you are looking for is an explanation of different ways that SQL Server can be utilized to handle extremely large tables and data sets being replicated across the database server instances.  There are multiple approachs to this problem and none of them are a silver bullet, but understanding the basics of each is a good way to make the right architecture choice.

Sharding

Database sharding is a way to take an enormous data set and partition it into a number of different file groups.  These individual filegroups can be stored all on a single server, multiple servers, or better yet through a RAID based Storage Area Network.

The bottom line here is that physical IO performance significantly improves when you are accessing records from only a few physical file groups than from an enormous filegroup in an unsharded dataset.

SQL Server does not have a cheap or easy way to do this out of box, nor do I know of any easy or cheap way to do this with other major database providers.  Once you start talking about shards then you are playing a different ball game altogether.

Distributed Partition Views

These enable well partitioned datasets to be accessed in such a way that one would only fetch the necessary records based on your partitioning strategy.  There is good information on MSDN about this with SQL Server.

Active Clustering

The concept of clustering is to take multiple SQL Server instances as nodes and have them work together on a single database, synchronized so that partitions on different file groups are being read and written to in a way that does not corrupt or damage the data, and in a way that scale up massively.

Peer to Peer Replication

In this setup all database servers have their own instance, and each should be configured to only affect their own little area of the schema.  Data is frequently out of date between them and needs to be synced through some outside process and schema changes can be extremely difficult to implement.  This is not the ideal way to handle this in your application.

I can't afford distributed partitions and massively scalable active clustering!

So you don't have upwards of a million to drop on some licenses and hardware for massively scalable solutions?  There is always the Cloud.  Azure and other SQL Server PaaS (Platform as a Service) solution providers can provide you the scalability that you need without the large upfront investment.  This is generally the easiest route to go.


问:
Algorithms for data structures in distributed system
The hash table data structure can be easily spread across multiple machines with a simple algorithm to distribute the keys:

```<code>machine_to_query = item_key % machine_count
</code>```

When you want to read and write key value pairs, you use the key to work out which machine stores the data, then you talk to that machine.  If you want a count of the total number of items, you'd need to request the count from each server and add them up.

What algorithms exist for efficiently managing data structures where the data is partitioned across multiple machines?  Distributed algorithms, not parallel algorithms.

How might something like a sorted array work in a distributed fashion?  Efficiently.

答:
I don't know about published books that have this kind of thing, but there are some real world examples you could look at.  Scala has a http://www.scala-lang.org/api/current/index.html#scala.collection.parallel.immutable.package">Parallel Immutable Collections package.  They have a few hash-backed things, but also a vector (implemented as a shallow tree - http://xuwei-k.github.com/scala-library-sxr/scala-library-2.10.0-M1/scala/collection/parallel/immutable/ParVector.scala.html">source code available) and a sequence.

I think collections are being rewritten in Java 8 as part of http://openjdk.java.net/projects/lambda/">Project Lambda so you could look into that too.  I expected source code to be available somewhere, but I can't find it after a brief search.  I think one key element (which I think you assume in your question) is that having a collection do its own concurrency management is a big win.  Instead of iterating over collections externally where every user has to manage the concurrency, the collection does some kind of map() or reduce() operation where it is passed a function that operates on each item or filters items and the collection manages its concurrency internally.

I think most of these use a divide-and-conquer approach, sending the divisions to various processors.  You might Google http://en.wikipedia.org/wiki/Amdahl%27s_law">Ahmdal's Law as a starting point because it governs the maximum possible performance gain from running any algorithm over multiple processors.  Also map-reduce and big-data.


问:
How to name a variable when the word is both a noun and a verb
I have run into a corner-case problem with the general guidance of:

nouns for variables

verbs for functions

Specifically, I have a case where the word is ambiguous - it can be either a verb or a noun.  And in some cases when we're discussing the application, it will be used both ways in the same sentence.

My intent is to make sure the program will remain readable to future developers as well as myself when I return to sections of code months later.

One of the examples is with a battery.  A battery has a charge and you can also charge() a battery.

I think that having both Battery.Charge and Battery.Charge(value) will be confusing to future developers.

My current solution is to simply pick a different word for one or both of those cases (the variable and the function).  My problem with that approach is the Battery object's variable and function for charge won't align with design discussions involving the Battery.

My question is if there is another / better way to handle this conflict in naming convention?

Some additional reading on the subject.  None really addressed the particular of my question.

Meaningful concise method naming guidelines

Naming conventions for variables

The selected answer from https://softwareengineering.stackexchange.com/questions/14169/what-naming-guidelines-do-you-follow

答: For the verb case, I think Charge is OK. For the noun case, would getCurrentChargeLevel work for you?


答:
In similar situations I try to find synonyms.  In this case I would use "recharge" for the verb.  The "re-" is slightly redundant, but the meaning is clear.  Using the simple "charge" for the remaining charge in the battery is ambiguous because it doesn't specify any physical units.  I would prefer "availableAmpHours", "hoursUntilRecharge" or something similar.  The units will depend on whatever is convenient for the application.

My personal preference is to use verbs only for functions that change state.  I use nouns for non-mutating functions.  I suppose it depends on your point of view.  At the machine level, non-mutating functions do something, but at the model level, they don't.

Title: How to name a variable when the word is both a noun and a verb

Body:
I have run into a corner-case problem with the general guidance of:

nouns for variables

verbs for functions

Specifically, I have a case where the word is ambiguous - it can be either a verb or a noun.  And in some cases when we're discussing the application, it will be used both ways in the same sentence.

My intent is to make sure the program will remain readable to future developers as well as myself when I return to sections of code months later.

One of the examples is with a battery.  A battery has a charge and you can also charge() a battery.

I think that having both Battery.Charge and Battery.Charge(value) will be confusing to future developers.

My current solution is to simply pick a different word for one or both of those cases (the variable and the function).  My problem with that approach is the Battery object's variable and function for charge won't align with design discussions involving the Battery.

My question is if there is another / better way to handle this conflict in naming convention?

Some additional reading on the subject.  None really addressed the particular of my question.

Meaningful concise method naming guidelines

Naming conventions for variables

The selected answer from https://softwareengineering.stackexchange.com/questions/14169/what-naming-guidelines-do-you-follow


问:
In memory collection vs database vs individual classes for infrequently changed objects
I have a ASP.NET application which puts the users through a series of forms in a wizard like fashion and has them fill out fields on the form. In code, these forms and fields are represented as "Step" objects, with a collection of "Field" objects as properties.

Currently I have only one Step class, and each individual step is an instantiation of this class with various identifying properties set on it, including the collection of fields. The step objects are persisted in a database and loaded using an ORM. Note these "Step" objects aren't actually responsible for tracking progress of a specific user, they're really just templates that describe step properties like name, display name, step order, etc. Progress is tracked through a series of "ItemStep" objects which basically link one of these "Step" templates to a specific "Project". "ItemSteps" store information about which steps are completed, locked, skipped, etc.

However, these step objects and the associated field objects are not designed to be configured by end users. Most changes to the objects would likely break the application without corresponding changes to the code. Given all of this, I see 3 possible things I can do.

Moving the steps and fields out of the database and into some sort of in memory collection. My basic thought process is to have a static collection that holds all the steps, which will be hidden behind my existing data access logic.

Create a new class for each step, and appropriately define equality methods so that two step objects of the same class are considered equal. Then instead of querying either my in memory repository, or my ORM, all I need to do is new up an instance of the appropriate step class. The only downside is I have to find some way to persist the relationship between an "ItemStep" in the database and the "Step" class it should be instantiated with.

Do nothing and keep everything as it is.

I figure 1 or 2 will result in a performance improvement since they'll be fewer trips to the database, and will streamline the process of application changes, since I won't have to worry about updating the database. And either 1 or 2 could also make it easier to build out a rich inheritance model around the steps, and move some logic onto the step class itself, instead of where it currently sits, inside my Presenters.

Of these three possible solutions, what would you reccommend?

答: I would recommend using a Cache framework to load the Step info from the database into memory upon the first usage.  Every other user should get the result from the Cache framework (memory) instead of it pulling from the database.  The Cache can be set to refresh itself every so often if you think this data will be changed from time to time (ex: once per week).  If you never expect the data to be changed, then you can turn the refresh off and only have it refresh when the server is restarted.  You can build all this yourself, but there are plenty of good cache frameworks out there already.</p>


问:
Should I return from a function early or use an if statement?
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read

答:
I prefer the early return.

If you have one entry point and one exit point then you always have to track the entire code in your head all the way down to the exit point (you never know if some other piece of code bellow does something else to the result, so you have to track it up until the exist). You do that no mater which branch determines the final result. This is hard to follow.

With one entry and multiple exists, you return when you have your result and don't bother tracking it all the way down to see that nobody does anything else to it (because there won't be anything else since you returned). It's like having the method body split into more steps, which each step with the possibility to return the result or let the next step try its luck.


答:
The branch is an optional execution path, whereas a decision is the result of a combination of conditions (i.e. a boolean expression).

Thus, there can be decisions without branches.

For example:

```<code>int fun(int a, int b) {
   return (a > 5) && (b < 15);
 }
</code>```

In the above function, (a > 5) is a condition, (b < 15)" is another condition. (a > 5)  && (b < 15) is a decision. And there is no branch.

Thus in this example, the decision coverage will be reached with only 2 tests, and the branch coverage on source code reach 100% with a single test.

Branch coverage at the assembly level would require the same two tests, but the question becomes tricky if you write the function like this:

```<code>int fun(int a, int b) {
   return (a > 5) & (b < 15);
 }
</code>```

There is still a boolean decision (computed with arithmetic operations) and the assembly would not have branches.

NASA's handbook on MCDC measurement clarifies this type of difference:
https://ntrs.nasa.gov/citations/20010057789

Title: Branch vs decision coverage question

Body:
The branch is an optional execution path, whereas a decision is the result of a combination of conditions (i.e. a boolean expression).

Thus, there can be decisions without branches.

For example:

int fun(int a, int b) {
   return (a > 5) && (b < 15);
 }

In the above function, (a > 5) is a condition, (b < 15)" is another condition. (a > 5)  && (b < 15) is a decision. And there is no branch.

Thus in this example, the decision coverage will be reached with only 2 tests, and the branch coverage on source code reach 100% with a single test.

Branch coverage at the assembly level would require the same two tests, but the question becomes tricky if you write the function like this:

int fun(int a, int b) {
   return (a > 5) & (b < 15);
 }

There is still a boolean decision (computed with arithmetic operations) and the assembly would not have branches.

NASA's handbook on MCDC measurement clarifies this type of difference:
https://ntrs.nasa.gov/citations/20010057789

ContentLicense: CC BY-SA 4.0


问:
When should user stories be combined and separated?
As a school project, we are rolling out our initial set of user stories. Should a user story record the original idea from a user, without combining them or separate them?

For example, John added that "I want to post multiple choice questions.", and Mike added that "Except multiple questions, I want to post true/false questions." David added that "I want a confirmation box before I add questions"

Do you leave those 3 user stories as it is, or you want to combine John's and Mike's as "I want to post multiple choice and true/false questions." and within this new user story a detail like "show a conformation box before clicking the add buttion"?

What do you choose?

答:
Stories should ideally meet the INVEST criteria: Individual, Negotiable, Valuable, Estimable, Small, Testable. Choose story granularity to reflect what can be potentially delivered.

Can you add multiple choice questions separately from true/false questions? Can you allow submitting question even if there's not a confirmation box? Is a true/false question a special kind of multiple choice question (with the choices being true/false).

There doesn't have to be a mapping between what users say and the resulting user stories. If a user's idea includes multiple sub-ideas, then split that into separate stories. If a user's idea just elaborates another user's idea, then combine them into one user story.

I disagree with Kevin's answer that "Show a confirmation story" isn't a story, because it could be. It might be very reasonable to have just a "submit" button and then later add a confirmation step.


问:
Why do we use story points instead of man days when estimating user stories?
In agile methodologies (e.g. SCRUM), the complexity/effort needed for user stories are measured in Story points. Story points are used to calculate how many user stories a team can take in an iteration.

What is the advantage of introducing an abstract concept (story points), where we can just use a concrete measurement, like estimated man-days? We can also calculate velocity, estimate coverage of an iteration, etc. using estimated man-days.

In contrast, story points are harder to use (because the concept is abstract), and also harder to explain to stakeholders. What advantage does it offer?

答: Mike Cohn's book "Agile Estimating and Planning" describes the advantages and disadvantages of estimating with "ideal days" or story points, so the quick answer to your question is that you don't have to estimate with story points. If it's more natural to estimate in ideal days, go right ahead.</p>


答:
A couple minutes is OK for unit tests. However, keep in mind that there are 3 major types of tests:

Unit tests -- test each "unit" (class or method) independently of the rest of the project

Integration tests -- test the project as a whole, usually by making calls into the program. Some projects I've seen combine this with regression tests. There is significantly less mocking here than unit tests

Regression tests -- test the completed project as a whole, as the test suite is an end user. If you have a console application, you would use the console to run and test the program. You never expose internals to these tests and any end user of your program should (in theory) be able to run your regression test suite(even though they never will)

These are listed in order of speed. Unit tests should be quick. They won't catch every bug, but they establish that the program is decently sane. Unit tests should run in 3 minutes or less or decent hardware. You say you only have 1000 unit tests, and they take 2-3 minutes? Well, that's probably OK.

Things to check:

Make sure to ensure that your unit tests and integration tests are separate though. Integration tests will always be slower.

Ensure that your unit tests are running in parallel. There is no reason for them not to if they are true unit tests

Ensure your unit tests are "dependency free". They should never access a database or the filesystem

Other than that, your tests don't sound too bad right now. However, for reference, one of my friend's on a Microsoft team has 4,000 unit tests that run in under 2 minutes on decent hardware(and it's a complicated project). It's possible to have fast unit tests. Eliminating dependencies(and mock only as much as needed) is the main thing to get speed.

Title: How do we make unit tests run fast?


问:
Is Ken Thompson's compiler hack still a threat?

Ken Thompson Hack (1984)

Ken Thompson outlined a method for corrupting a compiler binary (and other compiled software, like a login script on a *nix system) in 1984. I was curious to know if modern compilation has addressed this security flaw or not.

Short description:

Re-write compiler code to contain 2 flaws:

When compiling its own binary, the compiler must compile these flaws

When compiling some other preselected code (login function) it must compile some arbitrary backdoor

Thus, the compiler works normally - when it compiles a login script or similar, it can create a security backdoor, and when it compiles newer versions of itself in the future, it retains the previous flaws - and the flaws will only exist in the compiler binary so are extremely difficult to detect.

Questions:

I could not find any answers to these on the web:

How does this relate to just-in-time compilation?

Are functions like the program handling logins on a *nix system compiled when they are
run?

Is this still a valid threat, or have there been developments in
the security of compilation since 1984 that prevent this from being a
significant issue?

Does this affect all languages?

Why do I want to know?

I came across this while doing some homework, and it seemed interesting but I lack the background to understand in a concrete way whether this is a current issue, or a solved issue.

Reference Material

Overview

Some code

答:
First, my favorite writeup of this hack is called Strange Loops.

This particular hack could certainly (*) be done today in any of the major open source OS projects, particularly Linux, *BSD, and the like. I would expect it would work almost identically. For example, you download a copy of FreeBSD that has an exploited compiler to modify openssh. From then on, every time you upgrade openssh or the compiler by source, you will continue the problem. Assuming the attacker has exploited the system used to package FreeBSD in the first place (likely, since the image itself is corrupted, or the attacker is in fact the packager), then every time that system rebuilds FreeBSD binaries, it will reinject the problem. There are lots of ways for this attack to fail, but they're not fundamentally different than how Ken's attack could have failed (**). The world really hasn't changed that much.

Of course, similar attacks could just as easily (or more easily) be injected by their owners into systems like Java, the iOS SDK, Windows, or any other system. Certain kinds of security flaws can even be engineered into the hardware (particularly weakening random number generation).

(*) But by "certainly" I mean "in pricinciple." Should you expect that this kind of hole exists in any particular system? No. I would consider it quite unlikely for various practical reasons. Over time, as the code changes and changes, the likelihood that this kind of hack would cause strange bugs increases. And that raises the likelihood that it would be discovered. Less ingenious backdoors would require conspiracies to maintain. Of course we know for a fact that "lawful intercept" backdoors have been installed in various telecommunications and networking systems, so in many cases this kind of elaborate hack is unnecessary. The hack is installed overtly.

So always, defense in depth.

(**) Assuming Ken's attack ever actually existed. He just discussed how it could be done. He didn't say he actually did it as far as I know.

OwnerDisplayName: Andrew


答:
First, people are better at relative estimates than absolute estimate. The babylonians mapping and rating the relative brightness of stars is a great example. They didn't get the absolute figures right, but the order was mostly spot on even for very similar intensities.

The second advantage is that a prime reason for doing this exercise is to drive conversation.. If you start discussing in exact days, conversation may quickly derail.

As Napoleon said: the plan is worthless, planning is invaluable.

Third, the project manager does not have to edit all estimates, just because it turns out that estimates were off by a factor of, eg, 130%.

Title: Why do we use story points instead of man days when estimating user stories?

Body:
In agile methodologies (e.g. SCRUM), the complexity/effort needed for user stories are measured in Story points. Story points are used to calculate how many user stories a team can take in an iteration.

What is the advantage of introducing an abstract concept (story points), where we can just use a concrete measurement, like estimated man-days? We can also calculate velocity, estimate coverage of an iteration, etc. using estimated man-days.

In contrast, story points are harder to use (because the concept is abstract), and also harder to explain to stakeholders. What advantage does it offer?


答:
I think Story Point method has at least two important advantages over Man-day method:
First, it's easier to estimate in SP. SP is relative and human like us are better in relative than absolute estimation like man-day method.

Second, when you estimate in SP, you get "Team SP" not "Individual Manday". When you ask "How long this task will take?", Senior dev can give you 1 day but 5 days for a Junior. That's Man-day is up to who will take that task to done. If the owner is force to changed (and it will!) your must re-schedule everything. With SP, it still the same whoever take the task.


问:
In python, is it considered better to define a module with functions or a module with a class that contains functions?
In my code either of the above two options would work equally well but I am interested in finding out the pros and cons of both approaches.</p>

答:
It honestly depends on your needs.  Most of the time a module of functions will be what you're looking for.

Python classes (imho) shouldn't be thought of like classes in C# or C++ or Java, there needs to be a logical reason to group a set of functions into a larger parent, data structures would be a good example of this, you want a congruent set of functions that apply directly to the class instead of a loosely collected set of functions that are general purpose.

Module of Functions: general purpose, utility, and more "global" functions

Module of Class of Functions: grouped classes of similar needs, different linked list data types or audio processing functions or different tree types.

A module is for the overall hierarchical grouping of similar systems, I usually have all utility functions under a single module, all data under another, my data layer and connectors under a more "parent" type module. Since a module is just a mental grouping it's less about what types of systems are in it (classes or functions, honestly probably a mix of the two) and more about the logical connections between the systems under the module.


答:
In most cases adding a helping verb, adverb, or adjective is good enough to distinguish them and can actually help with understanding.  With your case of Charge and Charge() on a battery making it DeltaCharge() could show that it's a function that can handle either charging or discharging.

Delta (in cases where there's a change but ambiguous) is a modifier that I use and recommend to others all the time for handing change in state (even if the verb is semi-obvious).


答:
Does this affect all languages?

This attack primarily affects languages that are self-hosting. That is languages where the compiler is written in the language itself. C, Squeak Smalltalk, and the PyPy Python interpreter would be affected by this. Perl, JavaScript, and the CPython Python interpreter would not.

How does this relate to just-in-time compilation?

Not very much. It is the self-hosting nature of the compiler that allows the hack to be hidden. I don't know of any self-hosting JIT compilers. (Maybe LLVM?)

Are functions like the program handling logins on a *nix system compiled when they are run?

Not usually. But the question isn't when it is compiled, but by which compiler. If the login program is compiled by a tainted compiler, it will be tainted. If it is compiled by a clean compiler, it will be clean.

Is this still a valid threat, or have there been developments in the security of compilation since 1984 that prevent this from being a significant issue?

This is still a theoretical threat, but is not very likely.

One thing you could do to mitigate it is to use multiple compilers. For example, an LLVM Compiler which is, itself compiled by GCC will not pass along a back door. Similarly, a GCC compiled by LLVM will not pass along a back door. So, if you are worried about this sort of attack, then you could compile your compiler with another breed of compiler. That means that the evil hacker (at your OS vendor?) Will have to taint both compilers to recognize each other; A much more difficult problem.

Title: Is Ken Thompson's compiler hack still a threat?

Body:
Ken Thompson Hack (1984)

Ken Thompson outlined a method for corrupting a compiler binary (and other compiled software, like a login script on a *nix system) in 1984. I was curious to know if modern compilation has addressed this security flaw or not.

Short description:

Re-write compiler code to contain 2 flaws:

When compiling its own binary, the compiler must compile these flaws

When compiling some other preselected code (login function) it must compile some arbitrary backdoor

Thus, the compiler works normally - when it compiles a login script or similar, it can create a security backdoor, and when it compiles newer versions of itself in the future, it retains the previous flaws - and the flaws will only exist in the compiler binary so are extremely difficult to detect.

Questions:

I could not find any answers to these on the web:

How does this relate to just-in-time compilation?

Are functions like the program handling logins on a *nix system compiled when they are
run?

Is this still a valid threat, or have there been developments in
the security of compilation since 1984 that prevent this from being a
significant issue?

Does this affect all languages?

Why do I want to know?

I came across this while doing some homework, and it seemed interesting but I lack the background to understand in a concrete way whether this is a current issue, or a solved issue.

Reference Material

Overview

Some code


答:
This hack has to be understood in context. It was published at a time and in a culture where Unix running on all kinds of different hardware was the dominant system.

What made the attack so scary was that the C compiler was the central piece of software for these systems. Almost everything in the system went through the compiler when it was first installed (binary distributions were rare due to the heterogenous hardware). Everyone compiled stuff all the time. People regularly inspected source code (they often had to make adjustments to get it to compile at all), so having the compiler inject backdoors seemed to be a kind of "perfect crime" scenario where you could not be caught.

Nowadays, hardware is much more compatible and compilers therefore have a much smaller role in the day-to-day operation of a system. A compromised compiler is not the most scary scenario anymore - rootkits and a compromised BIOS are even harder to detect and get rid of.


答:
Hungarian Notation to the rescue. You can have intCharge and fcnCharge(value), thus avoiding confusion and not adding a crazy long name when three letters will work just fine.

Or you could just use the same name and let the IDE handle it. Creating a longer or different name may be just as confusing in the long run anyway.


答:
I'm surprised no one has mentioned Parkinson's Law yet.

Work expands so as to fill the time available for its completion.

Basically if you're estimating in any kind of time unit for large tasks, developers will tend to take the time they estimated to complete it or go over. When you estimate in a nebulous time like Story Points or Shirt Sizes you avoid this pitfall.


答:
No

The attack, as originally described, was never a threat. While a compiler could theoretically do this, actually pulling off the attack would require programming the compiler to

Recognize when the source code being compiled is of a compiler, and

Figure out how to modify arbitrary source code to insert the hack into it.

This entails figuring out how the compiler works from its source code, in order that it can modify it without breakage.

For instance, imagine that the linking format stores the data lengths or offset of the compiled machine code somewhere in the executable. The compiler would have to figure out for itself which of these need to be updated, and where, when inserting the exploit payload. Subsequent versions of the compiler (innocuous version) can arbitrarily change this format, so the exploit code would effectively need to understand these concepts.

This is high-level self-directed programming, a hard AI problem (last I checked, the state of the art was generating code that is practically determined by its types). Look: few humans can even do this; you would have to learn the programming language and understand the code-base first.

Even if the AI problem is solved, people would notice if compiling their tiny compiler results in a binary with a huge AI library linked into it.

Analogous attack: bootstrapping trust

However, a generalization of the attack is relevant. The basic issue is that your chain of trust has to start somewhere, and in many domains its origin could subvert the entire chain in a hard-to-detect way.

An example that could easily be pulled off in real life

Your operating system, say Ubuntu Linux, ensures security (integrity) of updates by checking downloaded update packages against the repository's signing key (using public-key cryptography). But this only guarantees authenticity of the updates if you can prove that the signing key is owned by a legitimate source.

Where did you get the signing key? When you first downloaded the operating system distribution.

You have to trust that the source of your chain of trust, this signing key, isn't evil.

Anyone that can MITM the Internet connection between you and the Ubuntu download server—this could be your ISP, a government that controls Internet access (e.g. China), or Ubuntu's hosting provider—could have hijacked this process:

Detect that you're downloading the Ubuntu CD image. This is simple: see that the request is going to any of the (publicly-listed) Ubuntu mirrors and asks for the filename of the ISO image.

Serve the request from their own server, giving you a CD image containing the attacker's public key and repository location instead of Ubuntu's.

Thenceforth, you will get your updates securely from the attacker's server. Updates run as root, so the attacker has full control.

You can prevent the attack by making sure the original is authentic. But this requires that you validate the downloaded CD image using a hash (few people actually do this)—and the hash must itself be downloaded securely, e.g. over HTTPS. And if your attacker can add a certificate on your computer (common in a corporate environment) or controls a certificate authority (e.g. China), even HTTPS provides no protection.


答:
Story Points reflect the complexity of the problem, and therefore, reflect the confidence (or risk) of how accurate the estimate is.

A Story with a high story point tells me that there's a lot going on with the user story that isn't concrete.

The idea is to see what's a good balance of varying story points.  If I'm being shown an iteration plan with stories with all high story points, this gives me little confidence that the iteration will be executed as expected and that we need to look at other stories for the iteration or start breaking stories down.

When communicating with a manager or Product Owner, high story points mean that it will be extremely hazy as to when they will get a particular feature.  One of the solutions to this is to break the story down and hopefully you'll have a combination of low and high story points to work with so that you can iteratively demonstrate progress to the Product Owner.


答:
The purpose of that speech wasn't to highlight a vulnerability that needs to be addressed, or even to propose a theoretical vulnerability that we need to be aware of.

The purpose was that, when it comes to security, we'd like to not have to trust anyone, but unfortunately that's impossible.  You always have to trust someone (hence the title: "Reflections On Trusting Trust")

Even if you're the paranoid type who encrypts his desktop hard-drive and refuses to run any software you didn't compile yourself, you still need to trust your operating system.  And even if you compile the operating system yourself, you still need to trust the compiler you used.  And even if you compile your own compiler, you still need to trust that compiler!  And that's not even mentioning the hardware manufacturers!

You simply can't get away with trusting no one.  That's the point he was trying to get across.


答:
Can your test environment run anywhere? If it can, use cloud computing to run the tests. Split the tests among N virtual machines. If the time to run the tests on a single machine is T1 seconds, then the time to run them split up, T2, could approach T2=T1/N. (Assuming each test case takes about the same amount of time.)
And you only have to pay for the VMs when you're using them. So you don't have a bunch of test machines sitting in some lab somewhere 24/7.
(I'd love to be able to do this where I work, but we're tied to specific hardware. No VMs for me.)</p>

Title: How do we make unit tests run fast?


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

答:
Code Complete, Second Edition by Steve McConnell.

Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma

I'm entirely self-taught, and I was fortunate enough to stumble upon an article (I've long since forgotten where) early on in my work that pointed me to these two books. The transformation of my code after I read those two books was staggering. I owe a lot to those authors.


问:
Are security exploits a fatality?
I'm asking this here and not on the security related site because this one is a question about "software architecture" and "development methodologies", which are both covered by the FAQ.

EDIT: I'm talking about purely remote root / admin software exploits.  Not about insider physically breaking into labs / companies / houses / networks / machines.

Everytime there's a blog entry or article about a new security exploit there are lots and lots of people basically writing that: "No software shall ever be secure, every single software out there can be exploited. Give any pirate sufficient time and he'll eventually exploit any high-target software."  This is a constant. These type of comments always get modded like crazy and most people seems to accept it as a fact.

And it really gets me wondering: can any software architecture and development methodologies be used to ever come up with secure software or is there something technical that prevents us from writing secure systems/programs/OSes/servers?

The more I think about it, the more I don't understand why we couldn't, technically, build 100% secure software.  All the way down from the OS and then up: browsers, plugins...

Note that I'm not interested in a discussion here: I want to know if technically there is something or not that can prevent, say, an OS, to be written in a 100% secure way and why it's that way.

Now if there's nothing technically that prevents us from writing a 100% secure OS and from then writing a 100% secure server, why hasn't it been done?  Does it means our architecture and development methodologies (and tools?) are deeply flawed?

答:
No, it means that the world isn't secure. Software, like any other human endeavor, can be breached, circumvented, or otherwise done in. The question is not whether we can make it 100% but whether the security in place will slow the aggressor down/annoy him enough to make it temporally or economically unfeasible for him to bother whilst not making it economically or temporally unfeasible for us.

Software is not perfect because humans are not perfect.

Title: Are security exploits a fatality?


答: 90% of unauthorized access comes from people within the network. Disgruntled accountants, bored secretaries, overly ambitious middle management...  Even if you make the technology 100% secure, there's still people to worry about.

Title: Are security exploits a fatality?

Body:
I'm asking this here and not on the security related site because this one is a question about "software architecture" and "development methodologies", which are both covered by the FAQ.

EDIT: I'm talking about purely remote root / admin software exploits.  Not about insider physically breaking into labs / companies / houses / networks / machines.

Everytime there's a blog entry or article about a new security exploit there are lots and lots of people basically writing that: "No software shall ever be secure, every single software out there can be exploited. Give any pirate sufficient time and he'll eventually exploit any high-target software."  This is a constant. These type of comments always get modded like crazy and most people seems to accept it as a fact.

And it really gets me wondering: can any software architecture and development methodologies be used to ever come up with secure software or is there something technical that prevents us from writing secure systems/programs/OSes/servers?

The more I think about it, the more I don't understand why we couldn't, technically, build 100% secure software.  All the way down from the OS and then up: browsers, plugins...

Note that I'm not interested in a discussion here: I want to know if technically there is something or not that can prevent, say, an OS, to be written in a 100% secure way and why it's that way.

Now if there's nothing technically that prevents us from writing a 100% secure OS and from then writing a 100% secure server, why hasn't it been done?  Does it means our architecture and development methodologies (and tools?) are deeply flawed?