答:
Cheapest hardware given to a consultant when the consultant cost more than 150$/hour.

Putting it in perspective a better hardware may at least make the job 30min more effective per day. That would give 30min * 20 days of work per month=600min/month =10hours/month > more that 1 day job = 10 hours*150$/hour = 1500$

Now wouldn't a consultant work more efficient if he/she had a 1500$ computer?
Would it make the consultant less irritated?

Now the problem seems to be that there two budgets, one for the consultant and one for the PC hardware.


问:
Type parameterized methods to avoid casting
In a library I am developing I have a factory method that looks a bit like:

```<code>public <T> T instantiate(Type targetType) {
    return ...;
}
</code>```

I am using a type parameterized method to avoid that users of my library have to cast every time they invoke it (that would be the case if I would have chosen to return Object).

Is there any reason this is not a good design choice ?.

I do not like that the programmer can invoke my method like:

```<code>String s = instantiate(Integer.class);
</code>```

Which is clearly wrong.

Unfortunately, the method requires a type and not a class, otherwise I could have written something like:

```<code>public <T> T instantiate(Class<T> targetClass) {
    return ...;
}
</code>```

答:
I've tried to do the same thing quite recently and I got into problems. Take a look at my question here: https://stackoverflow.com/questions/15389994/lazy-class-cast-in-java

Instead, I would add a second parameter to that method, the class object of the type T. Basically, your alternative combined with what you need:

```<code>public <T> T instantiate(Type targetType, Class<T> klass) {
    return ...;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've tried to do the same thing quite recently and I got into problems. Take a look at my question here: https://stackoverflow.com/questions/15389994/lazy-class-cast-in-java

Instead, I would add a second parameter to that method, the class object of the type T. Basically, your alternative combined with what you need:

public <T> T instantiate(Type targetType, Class<T> klass) {
    return ...;
}


问:
What is the best practice for saving TimeZones in the database?
We want to start collecting timezones for each of our addresses in the database. What is the best practice to store the timezones? How would you go about acquiring timezones for the existing address records? </p>

<p>I'm using Microsoft SQL server, .net mvc, C#. Any suggestions would be greatly appreciated. </p>

答:
The absolute best practice would be to use a database that supports the TIMESTAMP WITH TIMEZONE data type which was defined by SQL99.

SQL Server has a type called datetimeoffset that does everything TIMESTAMP WITH TIMEZONE can do except store the actual time zone.  All you can do is store an offset from UTC (e.g., 2013-05-04 12:34:56 -5:00), which means you'll have to determine that before storage based on the time zone.


问:
Saving multiple copies of a single image at different sizes
I'm building a file storage programme that will also display images in photo galleries to users who upload them. I was wondering if anybody could help me out.

My plan was if an image was wider than 500px then I would resize it to 500px (gallery and mobile use) width and 250px (thumbnail use) width

I have no serious experience with this so I was wondering if anybody could help me. How many different versions of a single image should I store and at what sizes. Thanks

答:
If you are using these images on your website, store them exactly in all different sizes you are going to use on your website.

Image Scaling is a very important factor in a website's performance, and saves bandwidth and page-load time.

Scale images in accordance to your need, as disk space doesn't costs much.

See what google has to say about image scaling https://developers.google.com/speed/docs/best-practices/payload#ScaleImages


问:
Transform math formula into code (line-line intersection)
I'm having hard times transforming a math formula to code. I can solve it on the paper easily, but it's hard for me to bring it into code form. Is it generally possible to bring a math formula directly into a program, or, if not, how can it be transferred?

Taking, for example, the Pythagorean Theorem: a² + b² = c². Having a and b defined in the code, it is straight forward to apply this formula.

```<code>c = sqrt(pow(a, 2) + pow(b, 2))
</code>```

Currently, I'm having hard times bringing the line-line intersection, that I've solved on paper, into my program. Assuming a line being defined as L: O + a * D, one can find the intersection of two lines by setting them as equal.

```<code>L1: O1 + a * D1
L2: O2 + b * D2

=> O1 + a * D1 = O2 + b * D2
</code>```

Using pen an paper, I would have already defined values and can solve the equation by splitting the equation into three sub-equations and applying simple substituion (I hope you can read my hand writing):

My actual problem

... is that substitution can not be applied algorithmically, or I don't know how to do. The equation L1 = L2 must be transformed to a generalized formula that can be directly translated into code (like a² + b² = c²), but I don't know how.

I was hoping for a step-by-step explanation (either as answer or linked) on how to come to the formula/algorithm I am searching for. I know there are quite many websites that describe the intersection of two lines, but I would like to understand how to find the algorithm from a mathematical starting point.

答:
I'd probably suggest taking a pair of the sub-equations and seeing if there is a unique solution that can then be used for the third line.  There are a few special cases to handle algorithmically:

If the two lines are in fact the same line.  This could be easily solved by seeing that D1 is a multiple of D2.  Note that in this case, all the points of the line are the intersection.

Standard case: Take the top pair of equations to get a system of 2 equations in 2 unknowns that could be solved via Matrix arithmetic.  It is possible to compute an inverse of a 2 x 2 matrix and thus this gives a solution if the determinant isn't zero.  This then gets applied to the other dimensions to see that the solution does in fact hold and if so is in fact a solution.

If the lines don't intersect.  Consider line 1 that goes through (0,0,1) and has slope (0,1,0) and line 2 that goes through (1,0,0) and has slope (0,0,1).  These lines don't intersect at all as all the points of the first line have an x-coordinate of 0 and the second line has an x-coordinate of 1.

At least, this is how I'd handle it programatically.  You could consider line 1 going through (a,b,c) with slope (d,e,f) and line 2 going through (g,h,i) and with slope (j,k,l) and consider the algebra to generate the formulas to do this in code.


问:
Documenting Function That Takes Random Parameters?
What's the best approach to creating documentation (displaying the function prototype if you will) for functions that take a variety of different forms in terms of parameters.

Let's say there are 10 different choices:

```<code>param(name);
param(name, type);
param(name, options);
param(name, type, options);
param(name, fn);
param(name, type, fn);
param(name, options, fn);
param(name, type, options, fn);
param(options);
param(options, fn);
</code>```

How would one write a function prototype (documentation) for these types of methods (even ones that don't come to this extreme)?

Some projects use function "overloading" in the documentation:

```<code>.on(event, fn, [capture])
.on(event, selector, fn, [capture])
</code>```

But would the length be outweighed by the clarity or flexibility?

答:
The reason projects use the overloading syntax is because it is easy and clear to read. There might be criticism about the jQuery library but it is one of the best documented libraries I know of in JavaScript, it's very easy to read.

Functions in that syntax have two purposes, either arguments are optional (like passing options to $.get in jQuery) or arguments change what the function does (overloading). These two cases are fundamentally different!

See how for example in jQuery the .css function is divided into:

```<code>.css( propertyName ) // gets a property value

.css( propertyName, value ) //sets a property value
</code>```

These perform fundamentally different tasks and need to be documented as different methods.

On the contrary the $.get method performs the same action but has optional prameters, which is why it is documented as such:

```<code>jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
</code>```

This makes it clear to us that the action performed is fundamentally the same but optional parameters give us hints about what we may pass to the method.

Body:
The reason projects use the overloading syntax is because it is easy and clear to read. There might be criticism about the jQuery library but it is one of the best documented libraries I know of in JavaScript, it's very easy to read.

Functions in that syntax have two purposes, either arguments are optional (like passing options to $.get in jQuery) or arguments change what the function does (overloading). These two cases are fundamentally different!

See how for example in jQuery the .css function is divided into:

.css( propertyName ) // gets a property value

.css( propertyName, value ) //sets a property value

These perform fundamentally different tasks and need to be documented as different methods.

On the contrary the $.get method performs the same action but has optional prameters, which is why it is documented as such:

jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

This makes it clear to us that the action performed is fundamentally the same but optional parameters give us hints about what we may pass to the method.


问:
Can I borrow parts of an apache-licensed project for something not open-source?
If I want to make a card game app or android, could I legally borrow parts of the Apache-2.0-licensed Solitaire-for-Android? Would I be able to charge such a project? (I was unable to understand the legal jargon in the license here.)</p>

答:
It's actually a very simple license, worth reading with due respect. If you can ask the question in English, I'm very sure you can comprehend the license - just try once again, without distractions.

In short, you can (section 3) IF you follow the rules (section 4 through 9). If you don't follow, then you are in violation.

Disclaimer: I'm not a lawyer and in your shoes, I'd get a legal opinion instead of a random dude online.


问:
Will I learn more from changing other people's code?
I am currently trying to break through the intermediate coder stage to advanced and needless to say it's been tough.

I have been working through several books with example code. I have felt lately that taking the example code, changing it to fit my own similar project, breaking it, and fixing it, is more effective for learning than simply re-coding line after line of example work.

Does anyone else similar or contrasting opinions? Will this method pay off in the long term?

Thoughts on this method of learning?

Thanks!

答:
I think you need a proper project: Find a problem to be solved, and solve it.

Doing something real (rather than hacking examples) will drill into your head all kinds of lessons: things that you have been taught that are good, things that don't work so well.

The biggest difficulty in a real project is not so much writing code, its knowing what code to write. That is, how to break up and structure the problem space. Get that wrong and the nicest code in the world is still a lousy solution.


答:
If you are doing this for a web site, and if you are using PHP, there are a set of library functions in PHP that will do this.

It's used for example as part of Wordpress - I expect you could download the source code and go poking around in there to see how its done. It's been years since I last looked in there so I can't be more specific.

Title: Saving multiple copies of a single image at different sizes

Body:
I'm building a file storage programme that will also display images in photo galleries to users who upload them. I was wondering if anybody could help me out.

My plan was if an image was wider than 500px then I would resize it to 500px (gallery and mobile use) width and 250px (thumbnail use) width

I have no serious experience with this so I was wondering if anybody could help me. How many different versions of a single image should I store and at what sizes. Thanks


答:
Reading other peoples code all the time is a sure shot way of improving your skills on the project. No doubt about it.

It also helps to be the dumbest guy in the team - by that I mean to say that if all the other programmers in the team are way above you in terms of programming skills it will automatically lift your level too - as long as you have the maturity to accept your limitations and ask for help. So leveraging skills of other team-mates is also important.

Reading code - apart from reading other people's code and asking them to explain their approach, pair programming is another good tool. Just sitting with a peer and observing their way of tackling a problem can set off light bulbs in you.  Also make it a habit to always review your own code - old code from time to time. I recall many times when I have visited a 100+ lines of code I wrote myself 2 months back and thought it was shit and refactored it much better.

Title: Will I learn more from changing other people's code?

Body:
I am currently trying to break through the intermediate coder stage to advanced and needless to say it's been tough.

I have been working through several books with example code. I have felt lately that taking the example code, changing it to fit my own similar project, breaking it, and fixing it, is more effective for learning than simply re-coding line after line of example work.

Does anyone else similar or contrasting opinions? Will this method pay off in the long term?

Thoughts on this method of learning?

Thanks!


问:
How do you stay motivated for hobby projects?
I started seriously programming as a hobbiest, student and then intern about 4 years ago and I've always done small projects on the side as a learning exercise.  Schools over now though, and I spend my days at work as a software developer. I would still love to do projects on the side to learn about areas in computer science that I'm not exposed to at work, but I've noticed that after 8 hours of starring at an IDE it's far to tempting to veg out.  Any time I do get up the gumption to work on something for a few hours lately it's gotten left by the wayside.

Anyone have any advice for sticking with side projects when you spend most of your day coding?

答:
I don't.  If I'm not motivated to code on a particular day or week or month, I go and do something I am motivated to do.

It's your free time, you shouldn't be forcing yourself to do things you don't want to do - that's what work is for...

ContentLicense: CC BY-SA 2.5


问:
What is the difference between a procedure-oriented and a problem-oriented programming language?
This is one of the questions given to us an assignment and I've tried to search for this on the internet but didn't get the required answers. Would be great if examples are provided too :)</p>

答:
You might want to begin your search with domain specific languages:

A domain-specific language (DSL) is a type of programming language or specification language in software development and domain engineering dedicated to a particular problem domain, a particular problem representation technique, and/or a particular solution technique.

I've never heard of a problem-oriented programming language, but a DSL sounds similar to what I imagine a problem-oriented programming language might be.


答:
I think the most important aspect of learning is failure.  When you attempt to adapt example code or implement something new and it doesn't work, you have to figure out why it doesn't work.

This is when your brain will be put to work attempting to solve the problem you have come across.  And when you finally have that 'aha!' moment, what you have learned from the initial failure will stick in your mind.

It's this process that is vital to becoming a better programmer.  Good programmers are good at figuring out how systems work, why they don't do what they should and how to fix them.  And the only way to get good at this is to practice solving problems when something fails to work.

If you do nothing but copy code from a book and run it it will always work (assuming no typos by yourself or the book) and you miss out on the vital experience of figuring stuff out for yourself.


问:
In functional programming, are local mutable variables with no side effects still considered "bad practice"?
Is having mutable local variables in a function that are only used internally, (e.g. the function has no side effects, at least not intentionally) still considered "non functional"?

e.g. in the "Functional programming with Scala" course style check considers any var usage as bad

My question, if the function has no side effects, is writing imperative style code still discouraged?

e.g. instead of using tail recursion with the accumulator pattern, what's wrong with doing a local for loop and creating a local mutable ListBuffer and adding to it, as long as the input is not changed?

If the answer is "yes, they are always discouraged, even if there is no side effects" then what is the reason?

答:
Having no local mutable variables does have one advantage--it makes the function more friendly towards threads.

I got burned by such a local variable (not in my code, nor did I have the source) causing a low-probability data corruption.  Thread safety wasn't mentioned one way or another, there was no state that persisted across calls and there were no side effects.  It didn't occur to me that it might not be thread safe, chasing a 1 in 100,000 random data corruption is a royal pain.


问:
I am new to programming and I am interested in jdbc - Tips and Advice needed
I am currently acquiring my associates degree in software engineering. I have been told in order to be successful in a computer science field you have to specialized in something. After researching several areas I have decided I want to specialize in Java Database Connectivity. It earns a decent income and seems interesting.

I would like to know what the field is like. What the job, bosses/managers, pay, etc...

I just want to know as much as I can first hand from the people that currently work in the field. What are some tips you would give a new-comer in college and what do you wish you had known before getting into the industry?

答:
As a software engineer/computer scientist your success doesn't depend on any specialization but rather your ability to solve problems, understand users and most importantly your ability to learn and apply new information.

JDBC is a technology used in the Java programming language to interact with databases. It's just one of the myriad of Java technologies you might encounter if you chose to learn Java. However it's not a good candidate for specialization as it's only one tiny part of the puzzle that is a software application.

Income, Stress, Bosses, Worklife, etc... will all depend on the companies you choose to work for. Some types of software development companies are known to have higher burn-out rates and worse working conditions on average (such as games). But your actual situation will vary greatly from company to company as with any other field.

What's most important is just to be interested in software. Write a pet-project or learn a language on your own initiative. You need to constantly excercise your learning muscles and learn how to write programs that help you solve a problem you have right now. As you learn more about programming it'll become easier to grasp difficult concepts. You don't need to study 24/7 but it's important that you enjoy the process of learning new concepts.


答:
Consider resizing the image not on upload but on demand (and caching the results).

This has a bonus feature; whenever you encounter a new use case that requires a new size, you can generate it easily by changing the parameters in the new code. It won't require you to run computation on your entire set of images all at once before it works.


问:
Source control system for binary files
At work we have a legacy system written in Visual FoxPRO.

Everything in foxpro is a table, even forms, so basically if you open a form file with a text editor you don't learn much.

Does anyone know about a tool for source control, that support merging and managing binary files? For now I'm converting what I can convert to text, use a text tool like to merge changes, and replace them manually, to get the team work in one version, then upload the stuff to a TFS server. I know it is not genius... please advise

答: I have a source conrol system that deals with all the issues of VFP files. Works well in multi user, multi project environment. Custom written ebcasue there is nothing out there that I could find that did the trick.</p>

Title: Source control system for binary files


问:
General thought process for "How would you build this website/app" interview questions
I've collected a bunch of interview questions like "Describe how you would design a photo album application", "Describe how you would design this particular feature of this particular website" (e.g. likes on Facebook, recommendation on Amazon, shopping cart, game of black jack). Then, what if there are millions of this thing? What would you change?

It looks like this is either expecting a database schema or a bunch of class definitions (or both?). I have learned about databases in school but I've never actually architected an application before and am having trouble knowing where to start, whether the designs I come up with are "good" and what I can change to make it scalable.

Is there a general approach or thought process when designing these systems? And general issues/problems that seem to come up a lot in the design that I should try to avoid? Could someone maybe walk me through one (or preferably all, while comparing the needs of each) of these and explain:

1) How do you come up with what entities are needed?
2) How do you decide on what relationships everything will have?
3) How do you incorporate performance optimization into your design?
4) Do I do this using classes or databases? Does it make a difference (i.e. would I have a class that can't really be translated to a database table, for example?)

The main reason I'm asking is because I was going through "Cracking the Coding Interview" and my answers were completely different from the author's - I had very different ideas of what classes were important.

MY ATTEMPT:
With the photo sharing app, I would have the classes/tables:
Photo and User for sure.

Then, I think if we're trying to create a schema, there would be a table linking photo and user if we assume each person in the photo is linked to the photo (is this table necessary? If not, is it still common practice to have a separate table for many-to-many relationships or not?).

But if we're trying to take an object oriented approach, maybe instead we'd have a class called album which does all the work and has all the info from the two other tables/classes. This is one thing I noticed in the book- there are a bunch of classes and then one class which basically has all the info and connects the other classes- is this common? For example, in my examples above, does this seem like it would apply?

I'm just hoping for some general rules/guidelines to follow because right now I have no idea how to tell what a good architecture for a large system looks like.

答:
The point of such questions is to assess whether you have real-world skills in writing a software application.  You have learned some theory, but theoretical knowledge can only go so far. The only way to truly understand software development is by doing it.

There is no shortcut to this, because there are no stock answers to questions like "what entities are needed?"  Instead, you have to apply your experience of various tools and paradigms, and how they work together, to come up with a practical solution to the problem at hand.

A question like "Do I do this using classes or databases?" suggests that you lack a basic knowledge of what things are and how they work.  Classes are a paradigm for organizing your code; databases are a method of data storage.  They are two inherently unrelated concepts (though they can work together). This is not an either/or question.

I don't mean to be harsh, but I think you need to develop your coding experience in order to succeed in such a job interview.  You certainly have the potential--your discussion of the photo sharing app has some of the right ideas and is headed in the right direction.  But you need to learn how this works firsthand.  The best way to prepare for your interview is to actually create an application from start to finish. A photo sharing app would be an appropriately sized project, or you could choose something else.  Your knowledge will really expand as you see how all the parts can work together to make a working application.


问:
Is it a good practice to create a ClassCollection of another Class?
Lets says I have a Carclass:

```<code>public class Car
{
    public string Engine { get; set; }
    public string Seat { get; set; }
    public string Tires { get; set; }
}
</code>```

Lets say we're making a system about a parking lot, I'm going to use a lot of the Car class, so we make a CarCollection class, it may has a few aditionals methods like FindCarByModel:

```<code>public class CarCollection
{
    public List<Car> Cars { get; set; }

    public Car FindCarByModel(string model)
    {
        // code here
        return new Car();
    }
}
</code>```

If I'm making a class ParkingLot, what's the best practice?

Option #1:

```<code>public class ParkingLot
{
    public List<Car> Cars { get; set; }
    //some other properties
}
</code>```

Option #2:

```<code>public class ParkingLot
{
    public CarCollection Cars { get; set; }
    //some other properties
}
</code>```

Is it even a good practice to create a ClassCollection of another Class?

答:
It's often handy to have domain-oriented methods to find / slice collections, as in the FindByCarModel example above, but there's no need to resort to creating wrapper collection classes. In this situation I will now typically create a set of extension methods.

```<code>public static class CarExtensions
{
    public static IEnumerable<Car> ByModel(this IEnumerable<Car> cars, string model)
    {
        return cars.Where(car => car.Model == model);
    }
}
</code>```

You add as many filter or utility methods to that class as you like, and you can use them anywhere you have IEnumerable<Car>, which includes anything ICollection<Car>, arrays of Car, IList<Car> etc.

Since our persistence solution has a LINQ provider, I'll frequently also create similar filter methods that operate on and return IQueryable<T>, so we can apply these operations to the repository too.

The idiom of .NET (well, C#) has changed a lot since 1.1. Maintaining custom collection classes is a pain, and you gain little from inheriting from CollectionBase<T> that you don't get with the extension method solution if all you need is domain-specific filter and selector methods.

Body:
It's often handy to have domain-oriented methods to find / slice collections, as in the FindByCarModel example above, but there's no need to resort to creating wrapper collection classes. In this situation I will now typically create a set of extension methods.

public static class CarExtensions
{
    public static IEnumerable<Car> ByModel(this IEnumerable<Car> cars, string model)
    {
        return cars.Where(car => car.Model == model);
    }
}

You add as many filter or utility methods to that class as you like, and you can use them anywhere you have IEnumerable<Car>, which includes anything ICollection<Car>, arrays of Car, IList<Car> etc.

Since our persistence solution has a LINQ provider, I'll frequently also create similar filter methods that operate on and return IQueryable<T>, so we can apply these operations to the repository too.

The idiom of .NET (well, C#) has changed a lot since 1.1. Maintaining custom collection classes is a pain, and you gain little from inheriting from CollectionBase<T> that you don't get with the extension method solution if all you need is domain-specific filter and selector methods.


答:
As you already suggest in your question, there is a big difference between implementing a formula, and implementing a calculation routine. Your paper solution is a routine, not a formula.

You needed paper to write down numbers as intermediate results. Your algorithm will need something similar. Algorithms for solving systems of equations typically manipulate a matrix (2D array) of numbers. Put your equation factors into an 2D array, and try to describe the substitions as an operation on that matrix.

When solving this on paper, you take decisions along the way. Eg. You choose to combine the first and third equation and solve that towards R. Then you used the second equation to solve p. This will not always work if there are some 0 factors in your equation. You might need to solve towards another variable, or combine the equations in a different order. The algorithm needs to take into account all these scenarios.

Your problem is 'overdetermined': In general, 2 lines in 3D will not intersect. It will require a 'lucky shot' (special case) for them to intersect. Your paper example happens to have a solution. And it happens to be round numbers: easy to check. What if your first solution for P would be 1.0 and your second solution would be 0.9999999? Would that be a rounding error of the algorithm, or would the problem have no solution?

Title: Transform math formula into code (line-line intersection)

Body:
I'm having hard times transforming a math formula to code. I can solve it on the paper easily, but it's hard for me to bring it into code form. Is it generally possible to bring a math formula directly into a program, or, if not, how can it be transferred?

Taking, for example, the Pythagorean Theorem: a² + b² = c². Having a and b defined in the code, it is straight forward to apply this formula.

```<code>c = sqrt(pow(a, 2) + pow(b, 2))
</code>```

Currently, I'm having hard times bringing the line-line intersection, that I've solved on paper, into my program. Assuming a line being defined as L: O + a * D, one can find the intersection of two lines by setting them as equal.

```<code>L1: O1 + a * D1
L2: O2 + b * D2

=> O1 + a * D1 = O2 + b * D2
</code>```

Using pen an paper, I would have already defined values and can solve the equation by splitting the equation into three sub-equations and applying simple substituion (I hope you can read my hand writing):

My actual problem

... is that substitution can not be applied algorithmically, or I don't know how to do. The equation L1 = L2 must be transformed to a generalized formula that can be directly translated into code (like a² + b² = c²), but I don't know how.

I was hoping for a step-by-step explanation (either as answer or linked) on how to come to the formula/algorithm I am searching for. I know there are quite many websites that describe the intersection of two lines, but I would like to understand how to find the algorithm from a mathematical starting point.


问:
Dynamic typing function arguments - how to keep readability high?
Dynamic typing newbie here, hoping for some wizened words of wisdom.

I'm curious if there is a set of best practices out there for dealing with function arguments (and let's be honest, variables in general) in dynamically typed languages such as Javascript. The issue I often run into is with regards to readability of code: I'm looking at a function I wrote a while ago and I have no clue what the structure of the argument variables actually is.  It's usually ok at the moment of development of new code: everything's fresh in my head, every variable and parameter makes sense because I just wrote them. A week later? Not so much.

For example, say I'm trying to crunch a bunch of data about user sessions on a website and get something useful out of it:

```<code>var crunchSomeSessionData = function(sessionsMap, options) {
    [...]
}
</code>```

Disregarding the fact that the function name isn't helpful - that obviously is a huge deal - I actually don't know anything at all about what the structure of sessionsMap or options is. Ok.. I have k/v pairs the sessionsMap object, since it's called Map, but are the value a primitive, an array, another hash of stuff? What is options? An array? A whitespace separated string?

I have a few options:

clarify the structure exactly in the comment header for the function. The problem is that now I have to maintain the code in two places.

have as useful of a name as possible. e.g. userIdToArrayOfTimestampsMap or even have some kind of pseudo-Hungarian dialect for variable naming that only I speak that explains what the types are and how they're nested. This leads to really verbose code, and I'm a fan of keeping stuff under 80 col.

break functions down until I'm only ever passing around primitives or collections of primitives. I imagine it might work, but then I'd likely end up with micro-functions that have one or two lines at most, functions that exist only for the purpose of readability. Now I have to jump all over the file and recompose the function in my head, which just made readability worse.

some languages offer destructuring, which to some extent can almost be thought of as extra documentation for what the argument type is going to contain.

could create a "class" for the specific type of object, even though it'd not make a huge difference in a prototypal language like JS, and would probably add more maintenance overhead than necessary. Alternatively, if available, one can try to use protocols, maybe something along the lines of Clojure's deftype/defrecord etc.

In the statically typed world this is not nearly as much of an issue. In C# for example you get a:

```<code>public void DoStuff(Dictionary<string, string> foo) {[...]};
</code>```

Ok, easy peasy, I know exactly what I'm getting, no need to read the function header, or go back to the caller and figure out what it's concocting etc.

What's the solution here? Are all people developing in dynamically typed languages continuously boggled by what types their subroutines are getting? Are there mitigation strategies?

答:
I think a lot of the problems that you are having can be solved with proper naming of variables and the contents of the method.  For the most part it should be obvious what the parameter types are based on the names and the contents of the method.  Documentation also helps.

For example:

```<code>function getSum(arr) {
    var sum = 0;
    arr.forEach(arr, function(item) {
        sum += item;
    });

    return sum;
}
</code>```

Just from the name of the function and how it is written it should be implied that getSum takes an array of numbers and returns a number.

Lets look at another example that doesn't make any sense irl but it should make sense what it is doing.

```<code>var crunchSomeSessionData = function(sessionsMap) {
    var browsers = {};

    Object.keys(sessionsMap).forEach(function(key) {
        var session = sessionsMap[key],
            browser = session.getBrowser();

        if(!browsers[browser]) {
            browsers[browser] = [];
        }

        browsers[browser].push(session.getUserId());
    });

    return browsers;
}
</code>```

Without proper documentation (irl this would be documented) you can still see that crunchSessionData takes an object of Session instances, those instances have a getBrowser and getUserId method.  It returns an object keyed off by browser that has an array of user ids that are currently on that browser.

```<code>crunchSomeSessionData({
    213j123j123j123j13: {browser: 'chrome', userId: 'pllee'},
    fawefjioawejfwoeiw: {browser: 'ie', userId: 'grandpa'}
})
>> {chrome: ['pllee'], ie: ['grandpa']}
</code>```

I would suggest that to get a good hang of how dynamic typing can be readable read some open source code that isn't heavily documented and see if you can follow what is going on.  If so start using their design patterns.  You can check out the simple performance timing library that I wrote https://github.com/pllee/vlug. It is very small and most of the methods aren't documented.  The code is not perfect but it could be a good example.  After not looking or using it for months the code still makes sense to me but I did write it :)

Body:
I think a lot of the problems that you are having can be solved with proper naming of variables and the contents of the method.  For the most part it should be obvious what the parameter types are based on the names and the contents of the method.  Documentation also helps.

For example:

function getSum(arr) {
    var sum = 0;
    arr.forEach(arr, function(item) {
        sum += item;
    });

    return sum;
}

Just from the name of the function and how it is written it should be implied that getSum takes an array of numbers and returns a number.

Lets look at another example that doesn't make any sense irl but it should make sense what it is doing.

var crunchSomeSessionData = function(sessionsMap) {
    var browsers = {};

    Object.keys(sessionsMap).forEach(function(key) {
        var session = sessionsMap[key],
            browser = session.getBrowser();

        if(!browsers[browser]) {
            browsers[browser] = [];
        }

        browsers[browser].push(session.getUserId());
    });

    return browsers;
}

Without proper documentation (irl this would be documented) you can still see that crunchSessionData takes an object of Session instances, those instances have a getBrowser and getUserId method.  It returns an object keyed off by browser that has an array of user ids that are currently on that browser.

crunchSomeSessionData({
    213j123j123j123j13: {browser: 'chrome', userId: 'pllee'},
    fawefjioawejfwoeiw: {browser: 'ie', userId: 'grandpa'}
})
>> {chrome: ['pllee'], ie: ['grandpa']}

I would suggest that to get a good hang of how dynamic typing can be readable read some open source code that isn't heavily documented and see if you can follow what is going on.  If so start using their design patterns.  You can check out the simple performance timing library that I wrote https://github.com/pllee/vlug. It is very small and most of the methods aren't documented.  The code is not perfect but it could be a good example.  After not looking or using it for months the code still makes sense to me but I did write it :)


答:
Certainly every server side Java developer should know JDBC, but it isn't a topic to specialize on, for three reasons:

The scope is very limited. You can grasp the concept in a day, and really grok the details in two or three weeks. It's just a thin layer over SQL, not enough fancy stuff to become a guru

Modern architectures are build on top of JDBC. You don't need to know much JDBC if you use JPA, Hibernate or other ORM frameworks.

In times of "big data" the NoSQL concept becomes more and more important, and obviously there is no JDBC for DBs like MongoDB. Some frameworks like Spring Data try to unify SQL and NoSQL sources.

Title: I am new to programming and I am interested in jdbc - Tips and Advice needed

Body:
I am currently acquiring my associates degree in software engineering. I have been told in order to be successful in a computer science field you have to specialized in something. After researching several areas I have decided I want to specialize in Java Database Connectivity. It earns a decent income and seems interesting.

I would like to know what the field is like. What the job, bosses/managers, pay, etc...

I just want to know as much as I can first hand from the people that currently work in the field. What are some tips you would give a new-comer in college and what do you wish you had known before getting into the industry?


问:
Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?
Lately I've been trying to split long methods into several short ones.

For example: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in process_url(), and then pass it over to process_components() function, which then passes the components to assign_components() function.

At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names.
However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods.

Continuing previous example: someone looking at the code might think that process_components() functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by process_url().

This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments.

Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods?

UPDATE: My main concern is that abstracting code into a function might imply that it could be called by multiple other functions.

SEE ALSO: discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode.

答:
Consider this simple function (I'm using Scala-like syntax but I hope the idea will be  clear without any knowledge of Scala):

```<code>def myFun ... {
    ...
    if (condition1) {
        ...
    } else {
        ...
    }
    if (condition2) {
        ...
    } else {
        ...
    }
    if (condition3) {
        ...
    } else {
        ...
    }
    // rest
    ...
}
</code>```

This function has up to 8 possible paths how your code can be executed, depending on how those condition evaluate.

This means that you'll need 8 different tests just to test this part. Moreover, most likely some combinations will not be possible, and then you'll have to carefully analyze what are they (and be sure not to miss some that are possible) - a lot of work.

It is very hard to reason about the code and its correctness. Since each of the if blocks and its condition can depend on some shared local variables, in order to know what's happening after them, everybody working with the code has to analyze all those code blocks and the 8 possible execution paths. It's very easy to make a mistake here and most likely somebody updating the code will miss something and introduce a bug.

On the other hand, if you structure the computation as

```<code>def myFun ... {
    ...
    val result1 = myHelper1(...);
    val result2 = myHelper2(...);
    val result3 = myHelper3(...);
    // rest
    ...
}

private def myHelper1(/* arguments */): SomeResult = {
    if (condition1) {
        ...
    } else {
        ...
    }
}
// Similarly myHelper2 and myHelper3
</code>```

you can:

Easily test each of the helper functions, each of them has only two possible paths of execution.

When examining myFun it is immediately obvious if result2 depends on result1 (just checking if the call to myHelper2(...) uses it to compute one of the arguments. (Assuming that the helpers don't use some global state.) It is also obvious how they're dependent, something that is much harder to understand in the previous case. Moreover, after the three calls, it's also clear how the state of the computation looks - it's captured just in result1, result2 and result3 - no need to check if/what other local variables have been modified.

Body:
Consider this simple function (I'm using Scala-like syntax but I hope the idea will be  clear without any knowledge of Scala):

def myFun ... {
    ...
    if (condition1) {
        ...
    } else {
        ...
    }
    if (condition2) {
        ...
    } else {
        ...
    }
    if (condition3) {
        ...
    } else {
        ...
    }
    // rest
    ...
}

This function has up to 8 possible paths how your code can be executed, depending on how those condition evaluate.

This means that you'll need 8 different tests just to test this part. Moreover, most likely some combinations will not be possible, and then you'll have to carefully analyze what are they (and be sure not to miss some that are possible) - a lot of work.

It is very hard to reason about the code and its correctness. Since each of the if blocks and its condition can depend on some shared local variables, in order to know what's happening after them, everybody working with the code has to analyze all those code blocks and the 8 possible execution paths. It's very easy to make a mistake here and most likely somebody updating the code will miss something and introduce a bug.

On the other hand, if you structure the computation as

def myFun ... {
    ...
    val result1 = myHelper1(...);
    val result2 = myHelper2(...);
    val result3 = myHelper3(...);
    // rest
    ...
}

private def myHelper1(/* arguments */): SomeResult = {
    if (condition1) {
        ...
    } else {
        ...
    }
}
// Similarly myHelper2 and myHelper3

you can:

Easily test each of the helper functions, each of them has only two possible paths of execution.

When examining myFun it is immediately obvious if result2 depends on result1 (just checking if the call to myHelper2(...) uses it to compute one of the arguments. (Assuming that the helpers don't use some global state.) It is also obvious how they're dependent, something that is much harder to understand in the previous case. Moreover, after the three calls, it's also clear how the state of the computation looks - it's captured just in result1, result2 and result3 - no need to check if/what other local variables have been modified.


问:
Not using SQL Transactions
I am looking at a codebase where a developer never uses SQL transactions i.e. each update/insert into the SQL database is an atomic operation.

I believe the codebase would benefit from transactions.  I was looking online today and in one Stackoverflow question an answerer says: "In some situations it is better to have a partial update rather than none at all".  Is there any truth in this? I suppose it depends on the problem domain to some extent.

答:
From the database perspective, frequent commits are often used to prevent records being unreadable by other sessions as they are locked by the updating session.

However this varies by RDBMS. Oracle has always had an MVCC system that prevented readers from blocking writers and writers from blocking readers, so it is not a problem there for instance.

Over-frequent committing on Oracle is strongly discouraged not only because it can leave partial transactions in the system but also because a COMMIT requires a synchronous redo log buffer flush which stalls the session (a high level of log_file_sync wait events is symptomatic of over-committing). Redo log buffers are asynchronously flushed every few seconds or when they are X% full anyway, so a longer running transaction may have less work to do during an explicit commit if it is deferred until the end of the business transaction anyway.

Title: Not using SQL Transactions


问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答:
We can save money by having the programmers double as testers/technical writers

If you are paying programmer salaries for tester/technical writer work, then you are wasting money and likely getting lower quality work than someone who has dedicated their career to that task. Also, when a programmer is up against a tight deadline testing and documentation are very likely to get dropped or done half-ass to meet it.

BTW: Developers are ALWAYS up against a tight deadline.


问:
What is the best practice for saving TimeZones in the database?
We want to start collecting timezones for each of our addresses in the database. What is the best practice to store the timezones? How would you go about acquiring timezones for the existing address records? </p>

<p>I'm using Microsoft SQL server, .net mvc, C#. Any suggestions would be greatly appreciated. </p>

答:
Assuming that you're using .Net framework 4.0 or higher, TimeZoneInfo is what you need.

Store all date values in the database in UTC format. Use either the ID value or the result of ToSerializedString() for each client to create a TimeZoneInfo object to convert stored dates to local format for display.


问:
JavaScript Frameworks for traditionally structured web applications
I am looking for a way to control large amounts of JavaScript code in a ASP.Net MVC web application.

I have been looking at Ember.js and whilst it's pretty compelling it takes control of the routing and as such treats the server as little more than a place from which to receive API calls. This isn't really useful for what I need.

I wondered if there recommendations for similar projects out there that allow faster, more structured, JavaScript but in traditional server-based web applications?

答:
Take a look at knockout.js it is an MVVM library.Like most frameworks it does not have any routing.Rather it has a concept of observables.What this means is it can observe any DOM elements for changes and once detected it updates the UI automatically.This can take care of most of the DOM interaction that we do in single page applications like showing/hiding certain parts of UI based on user actions.

For me knockout.js has the cleanest syntax in javascript frameworks.All the bindings are done through html 5 data* attributes.

You might also want to check out this excellent article that compares the most popular javascript mvc frameworks.If you already have written lots of client side code and are considering migrating to knockout.js check out this question that I asked on stack overflow.The answer really helped me in finding an effective way to do this.


答:
Absolute majority of programming work is done in a team and involves code base that already exists for some time and needs to be continuously adjusted for new requirements and features. You won't ever learn that from text book, you have to try it.

Working with other people's code is also great way to get experience how various idioms work in practice. You won't normally try to solve problem in all possible ways to see which one works better and you won't come up with that many ways yourself anyway. By reading existing code you will see various approaches to solving problems and learn what advantages which has in practice, so you can easily pick one when you need to design something yourself.

Lately there are many open source projects out there, so it should be easy to pick one that is interesting for you and contribute to it. You can start by fixing bugs or doing some small feature you think of. That's currently easiest way to get experience with some real programming work. You can even get grant for it from Google.


问:
Referencing countries via Foreign Key Constraint
To make things simple to explain: I've got two tables: Table1 and Countries.

The Countries table contains a nice flag and some information, such as DisplayName, the ISO3166 ALPHA3 code and the phone code (+49, +xx).

Table1 contains customers with a column Country.

Is it (in terms of usability, normalization and common human sense) okay to reference from Table1.CountryId to Countries.Id via a foreign key instead of having a plain Table1.Country nvarchar(255) field and insert a string into that?

答:
Not only is that ok, you absolutely should do it that way.

Only the Country table should have information about countries (such as the name).  All other tables that need to store a country should simply use CountryId, and this should be a foreign key to the Country table.

The reasons for doing this:

It avoids duplication.  It is a waste of space to store the country name and other similar info in multiple places. Storing the country name in both the Country table and elsewhere can use many times more space.  Suppose you have a million customers from a hundred different countries.  If you store the country name in the customer table, you have just increased the storage space used for country name by a factor of 10,000!

It removes ambiguity. If you store the country name in two places, you run the risk of having multiple versions of a country name.  You might have "USA", "U.S.A", "United States", etc.  This will be a mess to deal with.  Just using an ID field avoids this problem.

It is efficient.  Perhaps someone's reason to store the country by name in Table1 would be "well, then I don't have to join all the time to get the country name".  However, this is a false economy.  A join based on a numeric ID that is set to up as a foreign key will be trivial, performance-wise.  On the other hand, if you stored the name in both places and then needed to join based on the name, it would be far slower.


答:
I guess both are useful, but your coding on your own will be better.. Other's code will help, you will get to learn some things you couldn't have thought of but at that transition, it's how you think that matters.

It would be better if you take a few problems and solve them. Use other People's help when there are any problems that you can't get around. That way you will learn a lot more than by fiddling around with other's code.

When doing it all from scratch, you can understand every little thing of the code. Also, you will also learn from your mistakes(everyone makes them, and so will you).

When you type code, it's usually not what you type, but how you think of what to type, the logical analysis of the problem (and the inference/derivation of the solution) is what matters.


问:
Working alone on a project
So I am working on a small Project at my company, I am a mere trainee engineer (halfway through a Software Engineering degree), where we are developing an intranet - based project management and people management system - it incorporates Employee appraisals, personal skill management and development and so on.

Ive been working on this project for a little while, under the direction of a more senior engineer and there has been another trainee working on it too.

However soon, a big contract is coming up and the other two have been press-ganged for some of the work, which will tie them up for a long, long time.

This leaves me alone to work on this (really fun and full of learning) project alone. Dream come true! Or is it?

I've been worried about how I'm simply going to manage the work of three people, are there techniques, tools I can use? The more I think about it, the more intimidated I am (but still relishing the idea of a good challenge).

I have to think about planning, diagramming, release notes, test specs and my own hallways testing (where I grab a random person and say "break it!"), not to mention the actual programming work!

So in short, how can one person adapt to taking on the workload of three people?

答: If you mean that the distinct types of tasks were first divided among three, I suggest you request a weekly session (several hours) with the senior engineer to discuss progress, issues, ideas. It would be very unwise from the company standpoint to let you do it all alone, regardless of your level of expertise.</p>

Title: Working alone on a project


答:
Maybe try to write it more in OOP style. For example, instead of:

```<code>var crunchSomeSessionData = function(sessionsMap, options) {
    [...]
}
</code>```

why can't you do

```<code>session.crunchData(options)
</code>```

where session is object you have created. You will be able to take a look at constructor to know exactly how session is created and all your problems should go away

Title: Dynamic typing function arguments - how to keep readability high?

Body:
Dynamic typing newbie here, hoping for some wizened words of wisdom.

I'm curious if there is a set of best practices out there for dealing with function arguments (and let's be honest, variables in general) in dynamically typed languages such as Javascript. The issue I often run into is with regards to readability of code: I'm looking at a function I wrote a while ago and I have no clue what the structure of the argument variables actually is.  It's usually ok at the moment of development of new code: everything's fresh in my head, every variable and parameter makes sense because I just wrote them. A week later? Not so much.

For example, say I'm trying to crunch a bunch of data about user sessions on a website and get something useful out of it:

```<code>var crunchSomeSessionData = function(sessionsMap, options) {
    [...]
}
</code>```

Disregarding the fact that the function name isn't helpful - that obviously is a huge deal - I actually don't know anything at all about what the structure of sessionsMap or options is. Ok.. I have k/v pairs the sessionsMap object, since it's called Map, but are the value a primitive, an array, another hash of stuff? What is options? An array? A whitespace separated string?

I have a few options:

clarify the structure exactly in the comment header for the function. The problem is that now I have to maintain the code in two places.

have as useful of a name as possible. e.g. userIdToArrayOfTimestampsMap or even have some kind of pseudo-Hungarian dialect for variable naming that only I speak that explains what the types are and how they're nested. This leads to really verbose code, and I'm a fan of keeping stuff under 80 col.

break functions down until I'm only ever passing around primitives or collections of primitives. I imagine it might work, but then I'd likely end up with micro-functions that have one or two lines at most, functions that exist only for the purpose of readability. Now I have to jump all over the file and recompose the function in my head, which just made readability worse.

some languages offer destructuring, which to some extent can almost be thought of as extra documentation for what the argument type is going to contain.

could create a "class" for the specific type of object, even though it'd not make a huge difference in a prototypal language like JS, and would probably add more maintenance overhead than necessary. Alternatively, if available, one can try to use protocols, maybe something along the lines of Clojure's deftype/defrecord etc.

In the statically typed world this is not nearly as much of an issue. In C# for example you get a:

```<code>public void DoStuff(Dictionary<string, string> foo) {[...]};
</code>```

Ok, easy peasy, I know exactly what I'm getting, no need to read the function header, or go back to the caller and figure out what it's concocting etc.

What's the solution here? Are all people developing in dynamically typed languages continuously boggled by what types their subroutines are getting? Are there mitigation strategies?

Body:
Maybe try to write it more in OOP style. For example, instead of:

var crunchSomeSessionData = function(sessionsMap, options) {
    [...]
}

why can't you do

session.crunchData(options)

where session is object you have created. You will be able to take a look at constructor to know exactly how session is created and all your problems should go away


问:
moving from Windows to Linux
I need to reconcile these 2 facts:

I don't feel comfortable working on Linux;

I need to develop software for Linux.

Some background: I have a 10+ years of programming experience on Windows (almost exclusively C/C++, but some .NET as well), I was a user of FreeBSD at home for about 3 years or so (then had to go back to Windows), and I've never had much luck with Linux. And now I have to develop software for Linux. I need a plan.

On Windows, you can get away with just knowing a programming language, an API you're coding against, your IDE (VisualStudio) and some very basic tools for troubleshooting (Depends, ProcessExplorer, DebugView, WinDbg). Everything else comes naturally.

On Linux, it's a very different story. How the hell would I know what DLL (sorry, Shared Object) would load, if I link to it from Firefox plugin? What's the Linux equivalent of inserting __asm int 3/DebugBreak() in the source and running the program, and then letting the OS call a debugger? Why the hell release builds use something, called appLoader, while debug builds work somehow different? Worst of all: how to provision Linux development environment?

So, taking into account that hatred is usually associated with not knowing enough, what would you recommend? I'm ok with Emacs and GCC. I need to educate myself as a Linux admin/user, and I need to learn proper troubleshooting tools (strace is cool, btw), equivalents to the ones I mentioned above.

Do I need to do Linux from Scratch? Or do I need to just read some books (I've read "UNIX programming environment" by Kernighan and "Advanced Programming..." by Stevens, but I need to learn something more practical)? Or do I need to have some Linux distro on my home computer?

答:
The first question I'd ask is what is it that you want to develop? If it's a gui-based application then that can be different from having to write something like a kernel extension.

In the case of a gui app, I find the easiest method is to use Qt, which has its own development environment (Qt-Creator) and being cross-platform, allows you to learn just one API that can be used for Windows / Linux / OSX and even mobile development. Like visual studio in Windows, or XCode in OSX, you can create and layout windows and items from a graphical editor and the API is very easy to pick up with loads of sample applications.

If you need to get more low-level, then once you know your way around linux on the command line, know how to traverse directories, manipulate files, understand permissions etc., then either start reading how to compile a simple program with gcc, how to link files and run the executable and then how to debug with gdb.

Alternatively, if that seems a little daunting, you could download Eclipse or another IDE, but  you'll probably become much more comfortable with Linux in the long term, if you put the time and effort into the command line first.

OwnerDisplayName: rincewind

Title: moving from Windows to Linux


答:
Any code should be documented with enough information to understand it.  That includes information about the variable types if necessary (and even in statically typed languages, you may need more information than is supplied by just the type keyword).

When you get used to working with a dynamically-typed language, you will find that the type of a variable is often self-explanatory based on its use.  But if not, add comments to clarify it.

As for your concern that such comments add duplication (and possibly break a principle such as DRY), that concern would apply to any comment.  Any documentation inherently adds a certain amount of duplication, and must be maintained so that it matches the code.  But when it helps make the code understandable, the benefit outweighs the cost.

Also, note that most of your other solutions involve creating just as much (or more) extra stuff.  A class would need a class definition that is as least as large as the comments.  (Of course, making a class might be beneficial for other reasons.  But don't avoid solving this with comments just because they add extra lines to your code.)

Commenting should only be done when it is necessary to understand the code, however.  I hate seeing code like this, which really is useless duplication:

```<code>//crunchSomeSessionData - A function that crunches some session data.
//
//sessionsMap - A map containing the sessions and their data that we want to crunch.
//user - The user for whose sessions we want to crunch data
function crunchSomeSessionData(sessionsMap, user) {
    [...]
}
</code>```

Body:
Any code should be documented with enough information to understand it.  That includes information about the variable types if necessary (and even in statically typed languages, you may need more information than is supplied by just the type keyword).

When you get used to working with a dynamically-typed language, you will find that the type of a variable is often self-explanatory based on its use.  But if not, add comments to clarify it.

As for your concern that such comments add duplication (and possibly break a principle such as DRY), that concern would apply to any comment.  Any documentation inherently adds a certain amount of duplication, and must be maintained so that it matches the code.  But when it helps make the code understandable, the benefit outweighs the cost.

Also, note that most of your other solutions involve creating just as much (or more) extra stuff.  A class would need a class definition that is as least as large as the comments.  (Of course, making a class might be beneficial for other reasons.  But don't avoid solving this with comments just because they add extra lines to your code.)

Commenting should only be done when it is necessary to understand the code, however.  I hate seeing code like this, which really is useless duplication:

//crunchSomeSessionData - A function that crunches some session data.
//
//sessionsMap - A map containing the sessions and their data that we want to crunch.
//user - The user for whose sessions we want to crunch data
function crunchSomeSessionData(sessionsMap, user) {
    [...]
}


问:
How to time the sprints in Scrum to allocate time for TDD?
We have sprints of 4 weeks duration. What I have been doing is 3 weeks dev time and 1 week of pure manual/automated testing, stabilization and shipment assurance testing.

How to manage TDD within dev time? In my previous experience writing tests and getting 80% coverage requires round about 50% of the development time. Following the same we would get only 1 and a half week of development which is not enough.

My actual problem is how to allocate time for TDD? I want to make TDD a mandatory but with these it becomes really difficult for me. Do you think this is correct approach we are using or are we missing something and alter our approach to Scrum?

答:
I see a couple of problems and improvements here.

TDD is not only about coverage and ensuring tests are written, it is actually a design paradigm. Also, if you're TDDing correctly, you're automatically getting 100% coverage. Its a programming methodology. So you should consider it to be part of your coding activity.

Slicing your backlogs to optimal sizes is key to getting the right amount of work done in a sprint. If you notice too much work it probably means a big backlog. If the backlog is correctly sized then you are probably estimating more work than can be done in a sprint.

OwnerDisplayName: Haris


问:
How can I make being code reviewed by someone who doesn't know the language easier?
I'm in a team where I am the only Java developer. The rest of the team are VERY experienced in their own programming language, but their area of expertise is not object orientated.

I found the first time that I had a code review, it was a lengthy process that involved a lot of tangents about how Java works, or how OOP works etc. The second time, we got caught up on something and they had to bail as it was taking too long.

How can I make this process easier?

I desperately want my code reviewed as I myself am quite new to Java programming, and really to programming in general, but this is taking a long time (especially as, for instance I'm writing quite large chunks of code by refactoring old code that the last Java dev worked on).

答:
First of all, I'd start by introducing a lot of comments in your code where it makes sense to do so. So you wouldn't want to be commenting each line, but the concepts of what's happening. That way, it makes it easier for them to scan as they review the code.

Next, if as you say they don't have experience with object oriented programming, it may be an idea for you to do a presentation to the other group of programmers explaining OO concepts and how they map to functional languages (assuming that's what they are proficient in).

If the language they are coming from has a very different syntax and methodology (LISP to C++ for example(!)), then I think they're not really suited to be doing a code review for you.


答:
This could be difficult.

I think planning is your key. Do you have a project plan that the three of you are working to?

If not, I would suggest you come up with one before your colleagues jump ship. At the very least this will be a list of all the tasks you need to do on the project. The more detail the better (up to a point - but just saying "develop such-and-such a screen" is probably not detailed enough). Also include things like documentation and plans.

This is the top priority.

You should go through every task on the list and satisfy yourself that the time allowed for the task suits you. Its no good one of your colleagues estimating a day for a particular task, if its something you know nothing about and would likely take you a week.  Also be aware that developers tend to be optimistic about timescales - since you say you have little experience in this area you will likely fall into this trap. Unfortunately the main thing that will help you there is experience, but some "rules" that spring to mind could be:

nothing takes less than a half-day. Even if its a one-line code change. Because you'll lost the time elsewhere

however long you think it'll take, double it (this isn't one that I use because it cannot stand up to close scrutiny, but it may help you starting out)

if a single task takes longer than a week, you haven't defined it well enough. The reason for this is simply that if you have a 20-day task its near impossible to say with any certainty that you're 75% complete.

Depending on how important it is that you fit in with existing standards, you should add tasks (for other people) to review things like documentation, test plans and of course code. And you should add tasks (for yourself) to refactor your documentation/plans/code following these reviews.

If there are certain aspects of the project that you simply cannot do, or cannot do within a reasonable timeframe, or need training to do, say so.

Do not budget to work evenings or weekends. If you do this, and you slip, then you have no hope of making up the lost time. It may be that you feel the need to put in these extra hours, but you should use them to play catchup. Keep them up your sleeve, as it were.

Make sure your boss knows about this new plan, and is aware that delivery will take x weeks/months longer. If they want it more quickly, its up to them to either sort more resource or to descope parts of the project. This is important because if you don't communicate these things to your boss, they will be expecting you to deliver things when you're nowhere near ready.

Lastly, keep on top of your plan. If you are starting to slip, make sure you are the first to know. Now, whether you say anything to anyone or keep it to yourself will have to be a judgement call. If you're confident you can get the time back, then there's probably no point saying anything.

Bottom line is this: don't let yourself be stitched up. If you find yourself missing deadlines, your only defence will be if you can say, "Look, I highlighted this as a risk x months ago."

Title: Working alone on a project

Body:
So I am working on a small Project at my company, I am a mere trainee engineer (halfway through a Software Engineering degree), where we are developing an intranet - based project management and people management system - it incorporates Employee appraisals, personal skill management and development and so on.

Ive been working on this project for a little while, under the direction of a more senior engineer and there has been another trainee working on it too.

However soon, a big contract is coming up and the other two have been press-ganged for some of the work, which will tie them up for a long, long time.

This leaves me alone to work on this (really fun and full of learning) project alone. Dream come true! Or is it?

I've been worried about how I'm simply going to manage the work of three people, are there techniques, tools I can use? The more I think about it, the more intimidated I am (but still relishing the idea of a good challenge).

I have to think about planning, diagramming, release notes, test specs and my own hallways testing (where I grab a random person and say "break it!"), not to mention the actual programming work!

So in short, how can one person adapt to taking on the workload of three people?


答:
It looks like this is either expecting a database schema or a bunch of
  class definitions (or both?)

I think you're too focused on details here. With that question, the recruiter is not expecting a complete description of all classes you would write (otherwise they would ask you to code it, not talk about it).

Your answer first needs to be about the big picture - architecture, tiers, layers, even the project lifecycle and development process you would put in place. Don't hesitate to ask questions about the requirements and the environment the application is supposed to run in to adjust your answer. As dan1111 pointed out, there is no general recipe for a correct application design. All designs are context dependent.

Only if the recruiter starts asking really specific questions should you go into details about what classes, entities or database tables you would use under the hood.

Also, if you have little experience, it's only normal to say "I'll show you a solution using the type of application design I've been taught and used until now. I know of this and that other approaches which I can describe you in the large but have never really applied them. I'm also open to discovering and applying others".

There's nothing wrong with acknowledging that there are only so many tools in your toolbox that your experience allows you to have - in fact, it's better than spitting out a rehearsed answer which you have no clue how it works in practice.

Title: General thought process for "How would you build this website/app" interview questions

Body:
I've collected a bunch of interview questions like "Describe how you would design a photo album application", "Describe how you would design this particular feature of this particular website" (e.g. likes on Facebook, recommendation on Amazon, shopping cart, game of black jack). Then, what if there are millions of this thing? What would you change?

It looks like this is either expecting a database schema or a bunch of class definitions (or both?). I have learned about databases in school but I've never actually architected an application before and am having trouble knowing where to start, whether the designs I come up with are "good" and what I can change to make it scalable.

Is there a general approach or thought process when designing these systems? And general issues/problems that seem to come up a lot in the design that I should try to avoid? Could someone maybe walk me through one (or preferably all, while comparing the needs of each) of these and explain:

1) How do you come up with what entities are needed?
2) How do you decide on what relationships everything will have?
3) How do you incorporate performance optimization into your design?
4) Do I do this using classes or databases? Does it make a difference (i.e. would I have a class that can't really be translated to a database table, for example?)

The main reason I'm asking is because I was going through "Cracking the Coding Interview" and my answers were completely different from the author's - I had very different ideas of what classes were important.

MY ATTEMPT:
With the photo sharing app, I would have the classes/tables:
Photo and User for sure.

Then, I think if we're trying to create a schema, there would be a table linking photo and user if we assume each person in the photo is linked to the photo (is this table necessary? If not, is it still common practice to have a separate table for many-to-many relationships or not?).

But if we're trying to take an object oriented approach, maybe instead we'd have a class called album which does all the work and has all the info from the two other tables/classes. This is one thing I noticed in the book- there are a bunch of classes and then one class which basically has all the info and connects the other classes- is this common? For example, in my examples above, does this seem like it would apply?

I'm just hoping for some general rules/guidelines to follow because right now I have no idea how to tell what a good architecture for a large system looks like.


问:
How to maintain the 'LICENSE' file?
Many projects on Github comprise a LICENSE file, usually looking like:

```<code>Copyright (C) 2012-2013 Mr. Creator

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

...etc...
</code>```

My problems are:

If I create a project, should I add the name of every single contributor in LICENSE?

If I fork other's project, should I add my name in its LICENSE?

What if I add some files under another license?

答:
If I create a project, should I add the name of every single contributor in LICENSE?

You should add name of every copyright holder. Trivial changes cannot be copyrighted, so that makes it only the significant contributors.

I am used to slightly more complex layout though. File COPYING gives the license text and file AUTHORS gives the list of copyright holders. And the commit history would be more relevant in case of actual dispute about who is copyright holder anyway.

If I fork other's project, should I add my name in its LICENSE?

When you do some non-trivial changes yes. Or to whatever place they list copyright holders in (e.g. AUTHORS)

What if I add some files under another license?

Than you need to create a more complicated structure. Often than LICENSE lists which part is under which license, COPYING.license (COPYING.GPL, COPYING.MIT etc.) give the relevant license texts and AUTHORS lists the authors.

Each file still needs to list at least original author and which license applies to it.

Title: How to maintain the 'LICENSE' file?


答:
Make sure you get input from the more senior member regarding security. Employee information is not public record.

Here are some time savers:

Management Brains - Are they aware this started as the 3 person job and is now down to one? Someone has to do the math and adjust.

Existing applications. There are a lot of ways to build an app, but some of your coworkers are going to return to this project (formally or informally) and review your work. Try to use some of the best practices they've already included. The reasoning is part: Don't reinvent the wheel, they may have addressed needs that your infrastructure and/or company rules require, don't let their personal bias towards certain techniques/frameworks cloud their judgment of your work.

Requirements Adjustment - the app you're building could probably be bought off the shelf, so make sure you understand what your company needs that the other products don't offer. Make these your priority and adjust the other requirements along the way. You don't have to include all the bells and whistles they wanted upfront.

Team Overhead - You will have some advantage of not working with a team. You don't have to sit in meetings and debating your decisions. This will save time, but you do lose the input from what may be better devs/two heads are better than one. They may not be on the project, but do what you can to get some code review even if you have to treat them to lunch.

Time, Energy and Resource Management - Figure out when you perform the best and schedule the difficult programming tasks for those times. You will feel a little drained, so use those times to do some of the mundane administrative tasks. Don't forget social niceties and treat your hallway testers like gold. Listening to them talk about their cat is NOT a waste of time. Be the person they will take their time to help even though they have a full inbox.

Planning is good, but you have to get something built. Do the work and make plans, but don't spend too much time between coding. Good luck with your first app.

Title: Working alone on a project


答:
There are a whole bunch of various JavaScript frameworks.

You can find exemples of applications in there:
http://todomvc.com/

And a nice comparison here:
http://coding.smashingmagazine.com/2012/07/27/journey-through-the-javascript-mvc-jungle/

I personnally like Angular as it's more powerful then Knockout and lighter than Ember.

Title: JavaScript Frameworks for traditionally structured web applications

Body:
I am looking for a way to control large amounts of JavaScript code in a ASP.Net MVC web application.

I have been looking at Ember.js and whilst it's pretty compelling it takes control of the routing and as such treats the server as little more than a place from which to receive API calls. This isn't really useful for what I need.

I wondered if there recommendations for similar projects out there that allow faster, more structured, JavaScript but in traditional server-based web applications?


答:
Identifying countries by a foreign key is an excellent idea.  Using anything out of ISO 3166 is not:

The standard allows the same alphabetic codes to be re-used when a country undergoes a change.  For example, when East and West Germany were united, the entries for both countries were retired.  The new country retained West Germany's alphabetic codes (DE and DEU) and was given a new number.  The same happened when South Sudan split off from Sudan a couple of years ago:  Sudan's number was retired, new numbers were issued for both countries and Sudan kept its old alphabetic codes.

Some alphabetic codes may be re-used for other countries in the future.  The codes for Burma (which renamed itself Myanmar and retained its number) are transitionally reserved until 2040, when they go back into the pool and could potentially be issued to some other country.

The numeric codes have historically been unique, but not having a copy of the standard, I can't say for sure if they're guaranteed to stay that way.  With numbers in infinite supply, I imagine they won't be re-issued, but I wouldn't bet the integrity of my database on it.  The standard follows the numbers assigned by the United Nations Statistics Division, and the UNSD has already re-used the code  it used for Spanish North Africa (a territory) for South Sudan.

Bottom line:  maintain your own table with its own keys.

Title: Referencing countries via Foreign Key Constraint

Body:
To make things simple to explain: I've got two tables: Table1 and Countries.

The Countries table contains a nice flag and some information, such as DisplayName, the ISO3166 ALPHA3 code and the phone code (+49, +xx).

Table1 contains customers with a column Country.

Is it (in terms of usability, normalization and common human sense) okay to reference from Table1.CountryId to Countries.Id via a foreign key instead of having a plain Table1.Country nvarchar(255) field and insert a string into that?


问:
How to motivate team for knowledge sharing sessions
I work in a team with wide range of expertise and experience. I have been trying to introduce weekly knowledge sharing sessions. Sessions of 30-60 min length where everybody gets a chance to present something and talk about it. This will contribute in improving presentational and language skills.
However, the team is not motivated towards this, either the attendance is too low or none. How to get a team work towards such an idea?</p>

答:
what you can do is don't make it weekly session instead share knowledge on the go!
Encourage team members to ask questions and seek help from others when ever they face problem.

Identify people and interact with them frequently, seek their advcie, help and inputs.

This way you can achieve your goal.


问:
What would help when refactoring a large method to ensure that I don't break anything?
I'm currently refactoring a part of a large codebase with no unit tests whatsoever. I tried to refactor code the brute way, i.e. by trying to guess what the code is doing and what changes wouldn't change it meaning, but without success: it randomly breaks features all around the codebase.

Note that refactoring includes moving legacy C# code to a more functional style (the legacy code doesn't use any of the features of .NET Framework 3 and later, including LINQ), adding generics where the code may benefit from them, etc.

I can't use formal methods, given how much would they cost.

On the other hand, I presume that at least "Any refactored legacy code shall come with unit tests" rule should be strictly followed, no matter how much would it cost. The problem is that when I refactor a tiny part of a 500 LOC private method, adding unit tests appears to be a difficult task.

What can help me in knowing which unit tests are relevant for a given piece of code? I'm guessing that static analysis of the code would somehow be helpful, but what are the tools and techniques I can use to:

Know exactly what unit tests should I create,

And/or know if the change I've done affected the original code in a way that it is executing differently from now?

答:
I have had similar challenges.  The Working with Legacy Code book is a great resource, but there's an assumption that you can shoe-horn in unit tests to support your work.  Sometimes that's just not possible.

In my archeology work (my term for maintenance on legacy code like this), I follow a similar approach as to what you outlined.

Start with a solid understanding of what the routine is currently doing.

At the same time, identify what the routine was supposed to be doing. Many think this bullet and the previous are the same, but there is a subtle difference.  Often times, if the routine was doing what it was supposed to be doing then you wouldn't be applying maintenance changes.

Run some samples through routine and make sure you hit the boundary cases, relevant error paths, along with the mainline path.  My experience is that the collateral damage (feature breakage) comes from boundary conditions not being implemented in exactly the same way.

After those sample cases, identify what's being persisted that doesn't necessarily need to be persisted.  Again, I have found that it's side-effects like this that lead to collateral damage elsewhere.

At this point, you should have a candidate list of what's been exposed and / or manipulated by that routine.  Some of those manipulations are likely to be inadvertent.  Now I use findstr and the IDE to understand what other areas might reference the items in the candidate list.  I'll spend some time understanding how those references are working and what their nature is.

Finally, once I've deluded myself into thinking I understand the impacts of the original routine, I'll make my changes one-at-a-time and rerun the analysis steps I outlined above to verify that the change is working as I expect it to work.  I specifically try to avoid changing multiple things at once as I have found this blows up on me when I try and verify the impact.  Sometimes you can get away with multiple changes, but if I can follow a one-at-a-time route, that's my preference.

In short, my approach is similar to what you laid out.  It's a lot of prep work; then make circumspect, individual changes; and then verify, verify, verify.


问:
How to design an application that read files using MVC pattern?
I am going to write an application that reads data from a csv file, and display that data to the user. I intend to apply an MVC design pattern to create this application. A user will interact with this application through a console. Hence the view is a console.

There will be a Main.java that is responsible for :

Presenting a menu that a user can choose in the console.

Able to handle event in the console, e.g.: a user choose an option to read two csvfiles and ask the application to display differences between the two csv files.

Execute appropriate business logic for selected events.

To do this the Main.java will have a Main method that displays menu to a user in a console.

I am considering to make the Main.java as a Controller, because this class is responsible for taking the user input, and figure out what to do with the input. To do this, The Main.java will call a class called FileService.java, which is a service class. FileService.java is responsible for:

Read a csv file.

Display the content of the text file sorted according to some rule.

Display differences content of 2 csv files.

The FileService will parse the csv file using a csv parser, and stores the content of the files on a disk using  MapDB. The intention of using MapDB is to allow user read huge file (e.g.: 5 GB), and perform operations to the content of the file. Once the file has been read, Main.java could display the content of the file, or display the differences between the 2 text files, when a user select the option in the console.

The FileService is intended to be the Model part in this application. And, the FileService is completely decoupled from the view and the controller, which is the Main.java.

Does this simple design achieve separation of concern addressed by MVC ?

Response to @tgkprog:

where is the view? if main is the controller and FileService the model/ business part then you need a view class too.

Response : When I built a web application, a view would be, but not limited to, a JSP, or an HTML page. In the context of the CSV file reader application, what would be the equivalent of a HTML or a JSP page ? This is some thing that I am not sure. The menu displayed in the console can be simply achieved inside the main method of the Main.java.

if the files are 5mb then i think a console app will be quite inadequate to display differences unless there are very few?

Response: I could dump the difference in a text file, and let user view the text file. This would be more helpful for them I think. Thank you for pointing this out.

答:
In short, you want to create an MVC app that allows a user to identify a file; read the file; and then push the contents of that file into a database layer.  Additionally, you want to treat the file handling routines as a Model.

View

This will be your console application providing user input & feedback.

User can select a file (via whatever means you pick)

View will either call controller with file name / descriptor or leave it in a place where the controller can poll and pick it up.  I'd have the View call the Controller, but I'm just pointing out other ways of doing it.

Controller

Receives file name from View

Calls Model.FileServices with file name

Receives data returned from Model.FileServices, aka contents of file.

Calls Model.DBAccessLayer to store data returned from Model.FileServices.

Provide updates to View regarding transfer progress

Note, you'll end up with at least two Model modules.  One for the FileServices and one for the DBAccessLayer.

So that's all well and good, but as file sizes increase then your system may not have enough memory to handle the entire file contents.  There's a couple of options to resolve that issue.

Have the FileServices implement a skip-take type call.  This will allow you to pick up ### Byte blocks from the file and push to the DBA Model.

Implement a method within the Model.DBA that essentially creates a stream between the FileServices and the DBAccessLayer.  That would remove the Controller from acting as a traffic director, but it complicates the DBAccessLayer instead.

Of the two options, I would prefer the first as I think it more appropriately assigns responsibilities for the associated actions.


答:
What would help when refactoring a large method to ensure that I don't break anything?

Short answer: small steps.

The problem is that when I refactor a tiny part of a 500 LOC private method, adding unit tests appears to be a difficult task.

Consider these steps:

Move the implementation into a different (private) function and delegate the call.

```<code>// old:
private int ugly500loc(int parameters) {
    // 500 LOC here
}

// new:
private int ugly500loc_old(int parameters) {
    // 500 LOC here
}

private void ugly500loc(int parameters) {
    return ugly500loc_old(parameters);
}
</code>```

Add logging code (make sure logging doesn't fail) in your original function, for all inputs and outputs.

```<code>private void ugly500loc(int parameters) {
    static int call_count = 0;
    int current = ++call_count;
    save_to_file(current, parameters);
    int result = ugly500loc_old(parameters);
    save_to_file(current, result); // result, any exceptions, etc.
    return result;
}
</code>```

Run your application and do whatever you can with it (valid use, invalid use, typical use, atypical use, etc).

You now have max(call_count) sets of inputs and outputs to write your tests with; You could write a single test that iterates over all your parameters/result sets you have and executes them in a loop. You can also write an aditional test that runs a particular combination (to be used to quickly check passing over a particular i/o set).

Move // 500 LOC here back into your ugly500loc function (and remove logging functionality).

Start extracting functions from the big function (do nothing else, just extract functions) and run tests. After this you should have more little functions to refactor, instead of the 500LOC one.

Live happily ever after.

Body:
I'm currently refactoring a part of a large codebase with no unit tests whatsoever. I tried to refactor code the brute way, i.e. by trying to guess what the code is doing and what changes wouldn't change it meaning, but without success: it randomly breaks features all around the codebase.

Note that refactoring includes moving legacy C# code to a more functional style (the legacy code doesn't use any of the features of .NET Framework 3 and later, including LINQ), adding generics where the code may benefit from them, etc.

I can't use formal methods, given how much would they cost.

On the other hand, I presume that at least "Any refactored legacy code shall come with unit tests" rule should be strictly followed, no matter how much would it cost. The problem is that when I refactor a tiny part of a 500 LOC private method, adding unit tests appears to be a difficult task.

What can help me in knowing which unit tests are relevant for a given piece of code? I'm guessing that static analysis of the code would somehow be helpful, but what are the tools and techniques I can use to:

Know exactly what unit tests should I create,

And/or know if the change I've done affected the original code in a way that it is executing differently from now?

Body:
What would help when refactoring a large method to ensure that I don't break anything?

Short answer: small steps.

The problem is that when I refactor a tiny part of a 500 LOC private method, adding unit tests appears to be a difficult task.

Consider these steps:

Move the implementation into a different (private) function and delegate the call.

// old:
private int ugly500loc(int parameters) {
    // 500 LOC here
}

// new:
private int ugly500loc_old(int parameters) {
    // 500 LOC here
}

private void ugly500loc(int parameters) {
    return ugly500loc_old(parameters);
}

Add logging code (make sure logging doesn't fail) in your original function, for all inputs and outputs.

private void ugly500loc(int parameters) {
    static int call_count = 0;
    int current = ++call_count;
    save_to_file(current, parameters);
    int result = ugly500loc_old(parameters);
    save_to_file(current, result); // result, any exceptions, etc.
    return result;
}

Run your application and do whatever you can with it (valid use, invalid use, typical use, atypical use, etc).

You now have max(call_count) sets of inputs and outputs to write your tests with; You could write a single test that iterates over all your parameters/result sets you have and executes them in a loop. You can also write an aditional test that runs a particular combination (to be used to quickly check passing over a particular i/o set).

Move // 500 LOC here back into your ugly500loc function (and remove logging functionality).

Start extracting functions from the big function (do nothing else, just extract functions) and run tests. After this you should have more little functions to refactor, instead of the 500LOC one.

Live happily ever after.