答:
Students of The Hitch Hiker's Guide to the Galaxy will recall that the Ultimate Question (Answer: 42) was "What do you get when you multiply 6 by 9"

So, whilst the rebuilt Earth uses Base 10 (decimal) the original Earth used base 13.

This seemingly off-topic prologue is there to illustrate that our concept of numbers is because we use Base 10 (decimal) as a matter of routine. And whilst decimalisation reinforces the 10-ness, this doesn't have to be the case.

And since this is programmers.SE, then binary (true/false) and hexadecimal (byte packing) should be equally widely understood... by that I mean, to me, A(hex) is (nearly) as understandable a concept as 10(dec)

Or more esoterically, in days gone by, before grams and kilograms, we used oz/lb/st and people conceptually "got it" - in fact some of these other measures were more intuitive.

Title: Understanding binary numbers in terms of real world objects

Body:
When I represent a number in the decimal system, I have an intuitive knowledge of what it amounts to. For example take the number '10': I understand that it means 10 apples or 10 people... i.e I can count in the real world.

But as soon as the number is converted to any other system, this understanding no longer applies. For example 10 when converted to binary will be 1010...now what does this represent? Is there a way to understand this number 1010 in terms of counting objects in the real world?


问:
Is there ever a reason to do all an object's work in a constructor?
Let me preface this by saying this is not my code nor my coworkers' code. Years ago when our company was smaller, we had some projects we needed done that we did not have the capacity for, so they were outsourced. Now, I have nothing against outsourcing or contractors in general, but the codebase they produced is a mass of WTFs. That being said, it does (mostly) work, so I suppose it's in the top 10% of outsourced projects I've seen.

As our company has grown, we've tried to take more of our development in house. This particular project landed in my lap so I've been going over it, cleaning it up, adding tests, etc etc.

There's one pattern I see repeated a lot and it seems so mindblowingly awful that I wondered if maybe there is a reason and I just don't see it. The pattern is an object with no public methods or members, just a public constructor that does all the work of the object.

For example, (the code is in Java, if that matters, but I hope this to be a more general question):

public class Foo {
  private int bar;
  private String baz;

  public Foo(File f) {
    execute(f);
  }

  private void execute(File f) {
     // FTP the file to some hardcoded location,
     // or parse the file and commit to the database, or whatever
  }
}
```
<p>If you're wondering, this type of code is often called in the following manner:</p>
<pre class="lang-java prettyprint-override"><code>for(File f : someListOfFiles) {
   new Foo(f);
}
</code>```

Now, I was taught long ago that instantiated objects in a loop is generally a bad idea, and that constructors should do a minimum of work. Looking at this code it looks like it would be better to drop the constructor and make execute a public static method.

I did ask the contractor why it was done this way, and the response I got was "We can change it if you want". Which was not really helpful.

Anyway, is there ever a reason to do something like this, in any programming language, or is this just another submission to the Daily WTF?

答:
"I was taught long ago that instantiated objects in a loop is
  generally a bad idea"

Yes, may be you are recalling why we need the StringBuilder.

There are two schools of Java.

The builder was promoted by the first one, which teaches us to reuse (because sharing = identity to efficiency). However, in the beginning of 2000 I started to read that creating objects in Java is so cheap (as opposed to C++) and GC is so efficient that reuse is worthless and the only thing that matters is productivity of programmer. For productivity, he must write manageable code, which means modularization (aka narrowing the scope). So,

this is bad

```<code>byte[] array = new byte[kilos or megas]
for_loop:
  use(array)
</code>```

this is good.

```<code>for_loop:
  byte[] array = new byte[kilos or megas]
  use(array)
</code>```

I asked this question when forum.java.sun existed, and people agreed that they would prefer declaring the array as narrow as possible.

Modern java programmer never hesitates to declare a new class or create an object. He is encouraged to do so. Java gives all the reason to do so, with its idea that "everything is an object" and cheap creation.

Furthermore, modern enterprise programming style is, when you need to execute an action, you create a special class (or even better, a framework) that will execute that simple action. Good Java IDEs, that help here. They generate tons of crap automatically, as breathing.

So, I think your objects lack the Builder or Factory pattern. It is not decent to create instances directly, by constructor. A special factory class for every your object is advised.

Now, when functional programming is coming into play, creating objects becomes even simpler. You will create objects at every step as breathing, without even noticing this. So, I expect your code will become even more "efficient" in new era

"do not do anything in your constructor. It is for initialization only"

Personally, I see no reason in the guideline. I consider it a just another method. Factoring code out is necessary only when you can share it.

ContentLicense: CC BY-SA 4.0

Body:
"I was taught long ago that instantiated objects in a loop is
  generally a bad idea"

Yes, may be you are recalling why we need the StringBuilder.

There are two schools of Java.

The builder was promoted by the first one, which teaches us to reuse (because sharing = identity to efficiency). However, in the beginning of 2000 I started to read that creating objects in Java is so cheap (as opposed to C++) and GC is so efficient that reuse is worthless and the only thing that matters is productivity of programmer. For productivity, he must write manageable code, which means modularization (aka narrowing the scope). So,

this is bad

byte[] array = new byte[kilos or megas]
for_loop:
  use(array)

this is good.

for_loop:
  byte[] array = new byte[kilos or megas]
  use(array)

I asked this question when forum.java.sun existed, and people agreed that they would prefer declaring the array as narrow as possible.

Modern java programmer never hesitates to declare a new class or create an object. He is encouraged to do so. Java gives all the reason to do so, with its idea that "everything is an object" and cheap creation.

Furthermore, modern enterprise programming style is, when you need to execute an action, you create a special class (or even better, a framework) that will execute that simple action. Good Java IDEs, that help here. They generate tons of crap automatically, as breathing.

So, I think your objects lack the Builder or Factory pattern. It is not decent to create instances directly, by constructor. A special factory class for every your object is advised.

Now, when functional programming is coming into play, creating objects becomes even simpler. You will create objects at every step as breathing, without even noticing this. So, I expect your code will become even more "efficient" in new era

"do not do anything in your constructor. It is for initialization only"

Personally, I see no reason in the guideline. I consider it a just another method. Factoring code out is necessary only when you can share it.

ContentLicense: CC BY-SA 3.0


问:
How to learn to make better estimates?
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).

答:
First and most important, you have to define a process and stick by it. Include revising the plan at the end of each phase of the process. You can also revise the process, but in an orderly way.

Second, do some kind of design. Design is the first step to planning, you don't build a house without drawings.

Third, track time (effort). You should at least differentiate:

Analysis

Design

Code

Unit testing (include fixing defects)

Integration testing (include fixing defects)

Acceptance testing, with the user (include fixing defects)

It would be great if you measured the defects fixing effort for each testing type, but it adds complexity, so you can do it later on.

Fourth, identify key base items for estimating. For example:

Number of processes to be automated (Analysis)

Number of domain model entities (Design)

Number of forms and reports (Code)

Fifth, correlate base items and effort. For example:

Analysis effort = X man-hours / process to be automated

Design effort = Y man-hours / domain model entity

Code effort = Z man-hours / form (or report); number of forms = A * domain model entities

Unit testing effort = M% * Code effort

Integration testing effort = N% * Code effort

Acceptance testing effort = P% * Code effort

Sixth, keep track of performance and deviation from estimates for each project. So you can fine tune your correlation factors.

Seventh, repeat and improve. You will gain a lot of insight just at the end of the first project, by the third you will feel at ease planning and estimating.

Have a look at http://en.wikipedia.org/wiki/Personal_Software_Process, it really works.

ContentLicense: CC BY-SA 2.5

Title: How to learn to make better estimates?


问:
Understanding binary numbers in terms of real world objects
When I represent a number in the decimal system, I have an intuitive knowledge of what it amounts to. For example take the number '10': I understand that it means 10 apples or 10 people... i.e I can count in the real world.

But as soon as the number is converted to any other system, this understanding no longer applies. For example 10 when converted to binary will be 1010...now what does this represent? Is there a way to understand this number 1010 in terms of counting objects in the real world?

答:
A binary number denotes a sum of powers of two. 10102 means (from right to left) no one, a two, no four, an eight.

I'll try to give a more expansive explanation of the concept of bases here.

I would argue that a number is an abstract concept. When you read 10, it is not the real thing, it is merely one possible representation of an idea/concept that you cannot truly grasp.

10 (that is, 1 followed by a 0), is an encoding for this idea of "ten". Although we have may have developed some sort of intuition for this way of encoding numbers, there is a more fundamental system at work here.

143 for instance is 100 + 40 + 3, or: 3 ones, 4 tens and 1 hundred (ten tens). We can decompose any such number by their digits. The position of a digit determines its significance, i.e. what power of ten it counts:

As you can see, the digits denote the coefficients for a sum of powers of ten. We call this number (ten) the base.

Ten (as a concept) is not a special number. It just seems natural because we are so used to it.

We can freely choose virtually any basis we like. The meaning of each digit always depends on the base and is obtained as follows:

Thus, 143 (the encoding) can have a different meaning, depending on which base is implied (usually ten of course) but the base could just as well be 11:

With binary numbers, it works the exact same way, but the base is two of course.

For any encoding in a certain base, you need base-many distinct symbols to encode numbers. That is, for base ten, you need ten distinct symbols, for a base-two system, you need two distinct symbols, or for hexadecimal, you need sixteen distinct symbols. Also, you need to have the idea of a "successor", i.e. in the decimal system, the symbol "2" is the successor of the symbol "1".

In a system that uses the the special symbols 0 and 1 (with their common meaning), 10 is always the encoding for its base.

 "common meaning":  0*a = 0, 1*a = a

This system can be used to denote any objects that are enumerable.

In real world terms - visually

Try to imagine a series of objects starting at some point, continuing indefinitely.

For the purposes of this document, I'll use dots:

Zero . . . . . . . . . …

Every dot represents a number. naturally, each dot is the successor of the dot to its left.

One way to refer to a dot would be to assign a unique symbol to each dot. As you probably can imagine, without any system, this is going to be extremely cumbersome. Just to be able to count to one thousand, you would have to remember one thousand arbitrary symbols (the Chinese for example prove it's possible, but that's beside the point).

Let's just go with the assumption that it's cumbersome, and provide some shortcut: I'll just replace every fourth dot with a pipe:

Zero . . . | . . . | . . . | . …

Now, we have simplified the problem a bit, assuming we can reliably name which pipe we mean, we can name dots relatively to a pipe. For instance, I can say: The second point after pipe X. Or the second point after the third pipe to denote the number fourteen.

However, as numbers get bigger (or speaking visually: we zoom out, we are left with a series of pipes), it's extremely cumbersome to simply count the pipes and then refer to a dot relatively of one such pipe. We apply the same trick. We can replace every fourth pipe with an ampersand:

Zero . . . | . . . | . . . | . . . & . . . | . . . | . . . | . . . & . . .…

Now, it becomes easier to specify a certain pipe, we simply say which ampersand we mean. Going from that, we relatively specify the pipe, and going from that, we relatively specify the dot.

This is exactly what the base-notation does. It places these markers on every n-th object, different markers on every n-th marker, etc Thus, there are never n or more of the same markers in sequence.

In this case, we have encode numbers with the base four: 1234 refers to the first ampersand, the second pipe after that, and the third dot after that: The number twenty-seven.

Applying the aforementioned rule, we never need more than four distinct symbols to denote an arbitrary number in base four.

Proof: Let's assume we need more than four distinct symbols. This would imply, that I need to count four or more markers of the same kind from a given position. However, that is never necessary, since I replaced every fourth of these very markers with a different kind, I must be able to skip ahead. Thus, the premise is incorrect: Four distinct symbols are always enough.


问:
What is the purpose of Console in Sublime text editor?
I want to know what purpose does console solve in sublime text 2. This is invoked by pressing Ctrl+Shift+`

Is this a kind of debugger, or It just helps you to install packages.

答:
Sublime Text 2 has Python embedded, and the console let's you inspect the current editor state, and create python code directly in the console to manipulate that state. See the API reference to see what you can do.

Sublime Text 2 extensions are thus written in Python, and any logging they do ends up on that console as well. So indeed, you can see the console as a debugger as well, if there are any python exceptions they'd be printed to that console.


问:
Data classes: getters and setters or different method design
I've been trying to design an interface for a data class I'm writing. This class stores styles for characters, for example whether the character is bold, italic or underlined. But also the font-size and the font-family. So it has different types of member variables. The easiest way to implement this would be to add getters and setters for every member variable, but this just feels wrong to me. It feels way more logical (and more OOP) to call style.format(BOLD, true) instead of style.setBold(true). So to use logical methods instead of getters/setters.

But I am facing two problems while implementing these methods: I would need a big switch statement with all member variables, since you can't access a variable by the contents of a string in C++. Moreover, you can't overload by return type, which means you can't write one getter like style.getFormatting(BOLD) (I know there are some tricks to do this, but these don't allow for parameters, which I would obviously need).

However, if I would implement getters and setters, there are also issues. I would have to duplicate quite some code because styles can also have a parent styles, which means the getters have to look not only at the member variables of this style, but also at the variables of the parent styles.

Because I wasn't able to figure out how to do this, I decided to ask a question a couple of weeks ago. See Object Oriented Programming: getters/setters or logical names. But in that question I didn't stress it would be just a data object and that I'm not making a text rendering engine, which was the reason one of the people that answered suggested I ask another question while making that clear (because his solution, the decorator pattern, isn't suitable for my problem). So please note that I'm not creating my own text rendering engine, I just use these classes to store data.

Because I still haven't been able to find a solution to this problem I'd like to ask this question again: how would you design a styles class like this? And why would you do that?

答:
Part 1

This is a good design question. You are correct in detecting code smell concerning getters and setters. They generally indicate a design problem exposing the implementation details of your object.

Try to think in terms of what your objects should do - Tell, Don't Ask:

http://pragprog.com/articles/tell-dont-ask

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

Your first problem may be that you are trying to design "data classes". Rather than worry about the data (implementation details), think about the functionality. Again, what should your objects do? In your case, what do you want to do with character styles? Who (software-wise) cares about character styles? What do they need to do?

Hopefully that gets you started. Test driven development helps with these kinds of design problems. It forces you to think in terms of function not data.

On the contrary, if all you need is a data container, write a C-style struct class and go to town. I wouldn't recommend that, maintaining it will be a $@#%#.

Good luck!

Part 2

What you want is either a simple data class - skip the getters and setters completely, or you want to create a platform independent abstraction that places a facade (Facade Pattern) in front of the rendering and style setting. It simply provides an interface for setting styles and rendering. Your platform specific implementation does the dirty work (using NSTextView in your example).

The benefit of the simple data class is that it is initially simple to write. Its drawback is that you will have a hard time avoiding a giant tangle of if-else statements. You will also be lacking a clear place to make you platform specific rendering calls that use the styles. As the system's complexity grows, you may find it more diffcult to decide where implementation details go.

The facade is a more abstracted approach. The benefits are that it is more flexible and can be reused if you decide to port to another platform. Its drawbacks are more upfront development time.

The facade's public interface will provide what you need to set and remove styles as well as initiate rendering when the time comes.

The details of how you want to set styles are up to you. Use what ever system feels best. Simple getters and setters or a generic set and get that uses a dictionary internally works too (see boosts ptree if you are using C++). You could even take all (or default) styles at construction time. You could decide to not even expose mutators at that point. Your call. Perhaps you decide it is important to data drive the styles you support and use a configuration plus factory system (We can add more detail later if that is important to you). In fact different implementatios of the facade could provide different ways of approaching the problem. You could prototype a few and choose what works best.

The platform specific implementation of you facade abstraction will use the platform specific rendering system (NSTextView in your case) and the styles you have set to make the appropriate calls to the system. Simply inject the platform specific classes at construction (Dependency Injection), implement your render() method and you should be good to go.

Part 3

If your system design allows, you could take all styles for a particular element at construction time. This could allow you to avoid getters and setters completely if you chose to make your element immutable. Your would then have a simple, clean and possibly immutable abstraction in front of your character styles system. Immutable state generally leads to fewer bugs but does require you to operate under the premise that you cannot change things willy-nilly.

Taking this a step further, a configuration file might define the different style setups you have. Again this would require prior knowledge of what styles you are setting (similar to constructing with the styles above). Give the type of style you are seeking, say "heading", you might fetch the configuration for headings which specifies a larger, bold font.

These are just some ideas off the top of my head. Without further requirements gathering and use cases it will be tough to get more specific.

Hope that helps. Good luck!


问:
Maintaining C/C++/Java skills as a web developer
When I was in college I learned how to program in C, C++, and Java. Currently, I'm a web developer using front end and back end technologies (HTML/CSS/JS, PHP, MYSQL). While the sorting algorithms and OOP concepts that I learned in college can be applied to web development, I'm looking for ways to keep up my knowledge of all languages. I enjoy programming in C-Style (C/C++/Java) languages and front-end/back-end technologies. Unfortunately, there aren't many options to use C-style languages to build websites. However, I would like to keep up my knowledge and skills in the languages I learned in college as I know they will continue to help me with my growth.

What resources are available to keep challenging myself in C-style languages that are relevant to web development? Would contract work for C-style languages be beneficial? Are there sites that offer algorithm challenges? Any help is appreciated. I'm also interested in how others that have asked themselves this have solved this problem.

答:
For practicing algorithm challenges check out:

http://www.geeksforgeeks.org

https://class.coursera.org/algs4partI-2012-001/class/index


答:
Is there ever a reason to do all an object's work in a constructor?

No.

A constructor shouldn't have any side-effects.

Anything more than private field initialization should be viewed as a side-effect.

A constructor with side-effects breaks the Single-Responsibilty-Principle (SRP) and runs contrary to the spirit of object-oriented-programming (OOP).

A constructor should be light and should never fail.

For instance, I always shudder when I see a try-catch block inside a constructor. A constructor should not throw exceptions or log errors.

One could reasonably question these guidelines and say, "But I don't follow these rules, and my code works fine!"
To that, I would reply, "Well that may be true, until it isn't."

Exceptions and errors inside of a constructor are very unexpected. Unless they are told to do so, future programmers will not be inclined to surround these constructor calls with defensive code.

If anything fails in production, the generated stack trace may be difficult to parse. The top of the stack trace may point to the constructor call, but many things happen in the constructor, and it may not point to the actual LOC that failed.

I've parsed many .NET stack traces where this was the case.

Body:
Let me preface this by saying this is not my code nor my coworkers' code. Years ago when our company was smaller, we had some projects we needed done that we did not have the capacity for, so they were outsourced. Now, I have nothing against outsourcing or contractors in general, but the codebase they produced is a mass of WTFs. That being said, it does (mostly) work, so I suppose it's in the top 10% of outsourced projects I've seen.

As our company has grown, we've tried to take more of our development in house. This particular project landed in my lap so I've been going over it, cleaning it up, adding tests, etc etc.

There's one pattern I see repeated a lot and it seems so mindblowingly awful that I wondered if maybe there is a reason and I just don't see it. The pattern is an object with no public methods or members, just a public constructor that does all the work of the object.

For example, (the code is in Java, if that matters, but I hope this to be a more general question):

public class Foo {
  private int bar;
  private String baz;

  public Foo(File f) {
    execute(f);
  }

  private void execute(File f) {
     // FTP the file to some hardcoded location,
     // or parse the file and commit to the database, or whatever
  }
}
```
<p>If you're wondering, this type of code is often called in the following manner:</p>
<pre class="lang-java prettyprint-override"><code>for(File f : someListOfFiles) {
   new Foo(f);
}
</code>```

Now, I was taught long ago that instantiated objects in a loop is generally a bad idea, and that constructors should do a minimum of work. Looking at this code it looks like it would be better to drop the constructor and make execute a public static method.

I did ask the contractor why it was done this way, and the response I got was "We can change it if you want". Which was not really helpful.

Anyway, is there ever a reason to do something like this, in any programming language, or is this just another submission to the Daily WTF?


问:
Is catching general exceptions really a bad thing?
I typically agree with most code analysis warnings, and I try to adhere to them. However, I'm having a harder time with this one:

CA1031: Do not catch general exception types

I understand the rationale for this rule. But, in practice, if I want to take the same action regardless of the exception thrown, why would I handle each one specifically? Furthermore, if I handle specific exceptions, what if the code I'm calling changes to throw a new exception in the future? Now I have to change my code to handle that new exception. Whereas if I simply caught Exception my code doesn't have to change.

For example, if Foo calls Bar, and Foo needs to stop processing regardless of the type of exception thrown by Bar, is there any advantage in being specific about the type of exception I'm catching?

Maybe a better example:

```<code>public void Foo()
{
    // Some logic here.
    LogUtility.Log("some message");
}

public static void Log()
{
    try
    {
        // Actual logging here.
    }
    catch (Exception ex)
    {
        // Eat it. Logging failures shouldn't stop us from processing.
    }
}
</code>```

If you don't catch a general exception here, then you have to catch every type of exception possible. Patrick has a good point that OutOfMemoryException shouldn't be dealt with this way. So what if I want to ignore every exception but OutOfMemoryException?

答:
The two possibilities are not mutually exclusive.

In an ideal situation, you would catch all possible types of exception your method could generate, handle them on a per-exception basis, and in the end add a general catch clause to catch any future or unknown exceptions. This way you get the best of both worlds.

```<code>try
{
    this.Foo();
}
catch (BarException ex)
{
    Console.WriteLine("Foo has barred!");
}
catch (BazException ex)
{
    Console.WriteLine("Foo has bazzed!");
}
catch (Exception ex)
{
    Console.WriteLine("Unknown exception on Foo!");
    throw;
}
</code>```

Keep in mind that in order to catch the more specific exceptions, you must put them first.

Edit: For reasons stated in the comments, added a rethrow in the last catch.

Body:
The two possibilities are not mutually exclusive.

In an ideal situation, you would catch all possible types of exception your method could generate, handle them on a per-exception basis, and in the end add a general catch clause to catch any future or unknown exceptions. This way you get the best of both worlds.

try
{
    this.Foo();
}
catch (BarException ex)
{
    Console.WriteLine("Foo has barred!");
}
catch (BazException ex)
{
    Console.WriteLine("Foo has bazzed!");
}
catch (Exception ex)
{
    Console.WriteLine("Unknown exception on Foo!");
    throw;
}

Keep in mind that in order to catch the more specific exceptions, you must put them first.

Edit: For reasons stated in the comments, added a rethrow in the last catch.


答:
Pokemon exception handling (gotta catch em all!) is certainly not always bad. When your exposing a method to a client, especially an end user its often better to catch anything and everything rather than have your application crash and burn.

Generally though they should be avoided where you can. Unless you can take specific action based on the type of the exception its better not to handle it and allow the exception to bubble up rather then swallow the exception or handle it incorrectly.

Have a look at this SO answer for more reading.

Title: Is catching general exceptions really a bad thing?

Body:
I typically agree with most code analysis warnings, and I try to adhere to them. However, I'm having a harder time with this one:

CA1031: Do not catch general exception types

I understand the rationale for this rule. But, in practice, if I want to take the same action regardless of the exception thrown, why would I handle each one specifically? Furthermore, if I handle specific exceptions, what if the code I'm calling changes to throw a new exception in the future? Now I have to change my code to handle that new exception. Whereas if I simply caught Exception my code doesn't have to change.

For example, if Foo calls Bar, and Foo needs to stop processing regardless of the type of exception thrown by Bar, is there any advantage in being specific about the type of exception I'm catching?

Maybe a better example:

```<code>public void Foo()
{
    // Some logic here.
    LogUtility.Log("some message");
}

public static void Log()
{
    try
    {
        // Actual logging here.
    }
    catch (Exception ex)
    {
        // Eat it. Logging failures shouldn't stop us from processing.
    }
}
</code>```

If you don't catch a general exception here, then you have to catch every type of exception possible. Patrick has a good point that OutOfMemoryException shouldn't be dealt with this way. So what if I want to ignore every exception but OutOfMemoryException?


答:
Yes, catching general exceptions is a bad thing. An exception usually means that the program cannot do what you asked it to do.

There are a few types of exceptions that you could handle:

Fatal exceptions: out of memory, stack overflow, etc. Some supernatural force just messed up your universe and the process is already dying. You cannot make the situation better so just give up

Exception thrown because bugs in the code that you are using: Don't try to handle them but rather fix the source of the problem. Don't use exceptions for flow control

Exceptional situations: Only handle exception in these cases. Here we can include: network cable unplugged, internet connection stopped working, missing permissions, etc.

Oh, and as a general rule: if you don't know what to do with an exception if you catch it, it is better to just fail fast (pass the exception to caller and let it handle it)


答: It's not that it's bad, it's just that specific catches are better.  When you're specific, it means that you actually understand, more concretely, what your application is doing, and have more control over it.  In general, if you come upon a situation where you just catch an Exception, log it and continue, there's probably some bad things that are going on anyway.  If you're specifically catching the exceptions that you know a code block or method can throw, then there's a higher likelihood you can actually recover instead of just logging and hoping for the best.


答:
The topmost outer loop should have one of these to print all it can, and then die a horrific, violent and NOISY death (as this shouldn't happen and someone needs to hear).

Otherwise you should generally be very careful as you most likely have not anticipated everything that could happen at this location, and hence will most likely not treat it correctly.  Be as specific as possible so you only catch those you know will happen, and let those not seen before bubble up to the above mentioned noisy death.


问:
Is iron ruby on Silverlight a viable alternative to C#?
I've heard a lot of buzz about the Iron languages..

I mostly write line of business applications in c# and I'm not really enjoying c# these days.

Is IronRuby mature and fast enough to be used in silverlight right now?

As in am I gonna get a call in the middle of the night from an angry customer cause the silverlight app they depend on is buggy / grindingly slow?

答:
And most importantly, as far as I know, IronRuby + Visual Studio doesn't compile down to exe / dll so you'll have to give out your source code within your application.

I don't know if things changed recently, but I doubt it.


答:
These rules are generally a good idea and thus should be followed.

But remember these are generic rules. They don't cover all situations. They cover the most common situations. If you have a specific situation and you can make the argument that your technique is better (and you should be able to write a comment in the code to articulate your argument for doing so) then do so (and then get it peer reviewed).

On the counter side of the argument.

I don't see your example above as a good situation for doing so. If the logging system is failing (presumably logging some other exception) then I probably do not want the application to continue. Exit and print the exception to the output so the user can see what happened.


问:
Writing scripts for Visual Studio project
What is the best way to write and run small scripts and tasks that are specific to a particular .Net project?
Such things as configuring a database or confirming proper connections to servers.

In Ruby, I would build rake tasks for this sort of thing.

I am currently using unit tests for these tasks as they are easy to run within VS and they have access to all the necessary libraries and project code.  However, this is not really their intended purpose and, with the dropping of Test Lists in VS 2012, it does not work nearly as well as it used to.

Is there a better solution than writing a console project to handle these little code snippets I need to run periodically?

答: Powershell is the canonical answer if you need access to your project libs, as you wrote. However, for a lot of simple tasks I still use  "classic" Windows shell scripts, as long as the task can be easily solved with that. For example, simple file copy operations, folder creation etc. Another alternative is VBScript, if Windows shell script is not powerful enough. VBS misses direct access to .NET libs, but it has access to classic COM components, and was ok for me in the past for example for text file manipulation with regular expressions and similar things.</p>


答:
Catching general exception is bad because it leaves your program in an undefined state. You don't know where stuff went wrong so you don't know what your program has actually done or hasn't done.

Where I would allow catching all is when closing a program. As long as you can clean it up alright. Nothing as annoying as a program you close which just throws an error dialog that does nothing but sit there, not going away and preventing your computer from closing down.

In a distributed environment your log method could backfire: catching a general exception could mean your program still holds a lock on the log-file preventing other users from making logs.


问:
What is preferred for file I/O in Java?
Of the three

 BufferedReader/Writer

 Binary Streams

 Channels

which is more preferred in real life for file I/O in Java and why?

I prefer channels for binary data to be put into file or read from and BufferedReader/Writer for String data

答: The answer is "It depends" - Buffered, Streaming, Blocking and Non-blocking I/O are all used for different purposes depending on what concurrency, throughput and other performance characteristics that you're after.</p>

Title: What is preferred for file I/O in Java?


问:
Does Dart have any useful features for web programmers?
http://www.dartlang.org/

I've checked out the site very briefly, and got curious. Is there any advantages of using Dart? Is it just a replacement for JavaScript?

It looks like simpler Java. Writing quite a lot of C# at work, the language feels very much like what I'm used to, so learning the syntax looks like a breeze to learn. Has anybody any opinions or experiences with the language?

(Compared to CoffeeScript (= I'm not doing Ruby syntax) the syntax looks more familiar to me).

答:
Writing quite a lot of C# at work, the language feels very much like
  what I'm used to

That's one point about Dart.  Javascript is considered an awkward language with few general idioms.  In a language like Java there is often a natural way to approach a problem.  For instance if you keep an inventory of table, in Java or C# you will create a class Table.

Javascript has no classes, you might want to use prototypes but they feel awkward and don't provide such strong structure and encapsulation tools.  (At least not without making any stunts.)  Inheritance, composition etc. is awkward with Javascript prototypes.  That's why most people use plain hash maps to store data.  Or they use 3rd party libs like prototype which gives you a class-like experience.

So convenience is one thing, structure the other.  Javascript just doesn't scale well because there is no standard way to structure large-scale apps.  However currently such 3rd party libs are becoming really popular. (Like backbone.js)

Dart is something to solve that.  It's there to give you the stuctural convenience of Java and moreover it doesn't have all these awkward JS features.  (Most of them related to weak typing.)

So the answer is yes: classes, inheritance, ...: "traditional OOP".  (Most realworld JS webapps out there use jQuery's callback based approached as main structure.)  And it has a loose form of static typing, that's however not the key selling point.

BTW: you may want to read this "internal" Google mailing dated 2010: Future of Javascript

Javascript has fundamental flaws that cannot be fixed merely by evolving the
  language. We'll adopt a two-pronged strategy for the future of Javascript... Develop a new language (called Dash) that aims to maintain the dynamic nature of Javascript but have a better performance profile and be amenable to tooling for large projects...


答:
java.io uses Streams while java.nio use Channels and buffer, The most important distinction between java.io way and java.nio way is, how data is packaged and transmitted.java.io deals with data in streams (one byte at a time), whereas java.nio deals with data in blocks.
Processing data by the block can be much faster than processing it by the (streamed) byte but it is not as easy as streams.

In these situation, it is better to use java.io way:

Files may be large but not huge. It's possible to read an entire file into memory.

An application reads from or writes to only a few files or network connections at the same time, ideally using only one stream at a time.

The application is sequential. It won't be able to do much until it's finished reading or writing a file.

In these situation, it is better to use java.nio way:

An application that need to service hundreds or thousands of connections simultaneously.

You can see the following links for further information:

http://www.skill-guru.com/blog/2010/11/14/java-nio-vs-java-io-which-one-to-use/

http://blogs.oracle.com/slc/entry/javanio_vs_javaio

https://www.ibm.com/developerworks/java/tutorials/j-nio/

http://java.dzone.com/articles/java-nio-vs-io

Title: What is preferred for file I/O in Java?

Body:
Of the three

 BufferedReader/Writer

 Binary Streams

 Channels

which is more preferred in real life for file I/O in Java and why?

I prefer channels for binary data to be put into file or read from and BufferedReader/Writer for String data


问:
Is Object Oriented Programming a solution to complexity?
Do you think Object Oriented Programming is a solution to complexity. Why? This topic may be a bit controversial but my intentions to know the answer of Why from the experts here !</p>

答:
I think YES, just because it allows you to slice complexity into small self-containing "building blocks" that hide details, and then use them to create the functionality you need, step by step, layer by layer.

Divide and conquer.


问:
Parallel Threading in Multi-Language Software?
I'm developing a software that contain many modules/Daemon running in parallel manner, what i'm looking for is how to implement that, i cannot use Thread because some of those modules/Daemon are perhaps implemented in other languages (C,java,C#...).

For example I'm using C for Hooking Messages exchanged between Windows kernel and top level applications, Java/C# to use some free library to simply parse XML(for example) or to accept and execute commands over the network..this can be done by C Language but just to improve productivity...
Finally for GUI I'm using Ultimate++ (c++) that is like the main process that call and monitor(activate/deactivate/get state) of all other modules/Daemon through an interface.

I admit that the development of each module/Daemon in a separate language greatly facilitates maintenance, but especially I am obliged to do that..
What is the best practice way to do that ?

All helps will be appreciated.

答: Message passing  is probably a good option.  On UNIX pipes and sockets would be a standard way to accomplish that.  (Windows has similar concepts.)  In fact this even simplifies concurrency because you don't share any memory.</p>


答:
I'm going to go against the tide here -- in languages where everything has to be in some class AND you can't have a static class, you can run into the situation where you have an isolated bit of functionality that needs to be put somewhere and doesn't fit with anything else.  Your choices are a utility class that covers various unrelated bits of functionality, or a class that does basically just this one thing.

If you have just one bit like this, then your static class is your specific class.  So, either you have a constructor that does all the work, or a single function that does all the work.  The advantage of doing everything in the constructor is that it happens just once, it allows you to use private fields, properties and methods without worrying about them being reused or threading. If you have a constructor/method you may be tempteded to let the parameters be passed to the single method, but if you use private fields or proprties that introduces potential threading issues.

Even with a utility class, most people won't think to have nested static classes (and that might not be possible either depending upon the language).

Basically this is a relatively understandable way of isolating the behavior from the rest of the system, within what is allowed by the language, while still allowing you to take advantage of as much of the language as possible.

Frankly I would have answered much as your contractor did, it's a minor adjustment to turn it into two calls, there's not all that much to recommend one over the other. What dis/advatanges there are, are probably more hypothetical than actual, why try to justify the decision when it doesn't matter and it probably wasn't so much decided as just the default action?

Title: Is there ever a reason to do all an object's work in a constructor?


问:
Learning OO for a C Programmer
I've been programming professionally in C, and only C, for around 10 years in a variety of roles.

As would be normal to expect, I understand the idioms of the language fairly well and beyond that also some of the design nuances - which APIs to make public, who calls what, who does what, what is supposed to reentrant and so on. I grew up reading 'Writing Solid Code', it's early C edition, not the one based on C++.

However, I've never ever programmed in an OO language. Now, I want to migrate to writing applications for iPhone (maybe android), so want to learn to use Objective-C and use it with a degree of competence fitting a professional programmer.

How do I wrap my head around the OO stuff? What would be your smallest reading list suggestion to me.

Is there a book that carries some sort of relatively real world example OO design Objective-C?

Besides, the reading what source code would you recommend me to go through.

How to learn OO paradigm using Objective-C?

答:
There's nothing inherently special about one having C(or any other procedural programming language) background when learning a new programming paradigm. Except for the fact that it's very easy to stick to the old ways for whatever reasons; be that misunderstanding of the new concepts, finding them tiresome to stick to and so on.

The only real, valuable way is to practice. Of course, first you need to build some understanding about what to practice. As for a book, I can't recommend one apart from advising you to take a look what Amazon has to offer(read the table of contents and some reviews at least). Any decent Objective-C book should explain the basic concepts regarding object oriented programming to get you well started.

However, a single book is often not enough. There are books dedicated for object oriented programming and design patterns, such as Design Patterns: Elements of Reusable Object-Oriented Software (The Gang Of Four book). There are many others too, so choose your favourite among catalogue you are most familiar with.

Title: Learning OO for a C Programmer


问:
Fitting it together, database, reporting, applications in C#

Introduction

Preamble

I was hesitant to post this, since it's an application whose intricate details are defined elsewhere, and answers may not be helpful to others. Within the past few weeks (I was actually going to write a blog post about this after I finished) I've discovered that the barrier I'm encountering is one that's actually quite common for newer developers.

This question is not so much about a specific thing as it is about piecing those things together.

I've searched the internet far and wide, and found many tutorials on how to create applications that are kind of similar to what I'm looking for. I've also looked at hiring another, more experienced, developer to help me along, but all I've gotten are unqualified candidates that don't have the experience necessary and won't take care of the client or project like I will. I'd rather have the project never transpire than to release a solution that is half-baked.

I've asked professors at my school, but they've not turned up answers to my question. I'm an experienced developer, and I've written many applications that are -- very abstractly -- close to what I'm doing, but my experiences from those applications aren't giving me enough leverage to solve this particular problem.

I just hope that posting this article isn't a mistake for me to write.

Project Description

I have a project I'm working on for a client that is a rewrite of an application, originally written in Foxpro 2.6 by someone before me, that performs some analysis (which, sadly, I'm not allowed to disclose as per of my employment contract) on financial data.

One day, after a long talk between the client and I -- where he intimately described his frustrations with all the bugs I've been hacking out of this code for 6 months now -- he told me to just rewrite it and gave me a month to write a good 1/8 of this 65k LOC Foxpro monstrosity.  this 65k line of code foxpro monstrosity. It'll take me a good 3 - 6 months to rewrite this software (I know things the original programmer did not, like inheritance) going as I am right now, but I'm quickly discovering that I'm going to need to use databases.

Prior to this contract I didn't even know about foxpro, and so I've had to learn foxpro on the fly, write procedures and make modifications to the database. I've actually come to like it, and this project would be rewritten in Foxpro if it were still a supported language, because over the past few months, I've come to like the features of Foxpro that make it so easy to develop data-driven applications.

I once perfomed an experiment, comparing C# to Foxpro. What took me 45 minutes in C# took me two in Foxpro, and I knew C# prior to Foxpro.

I was hoping to leverage the power of C#, but it intimidates me that in foxpro, you can have one line of code and be using a database.

Prior to this, I have never written any serious database development from scratch. All the applications that I've written are in a different league. They are either completely data-naive or data-naive enough that I can get away with not using a database through serialization or by designing algorithms that work with the data in a manner that is stateless, so there is no need to worry about databases.

I've come to realize, very quickly, that serialization and my efficacy with data structures has been my crutch all these years that's prevented me from adventuring into databases, and has consequently hindered my success in real-world programming.

Sure, I've written some database stuff in Perl and Python, and I've done forms and worked with relational databases and tables, I'm a wizard in Access and Excel (seriously) and can do just about anything, but it just feels unnatural writing SQL code in another language...

I don't mind writing SQL, and I don't It's that bridge between the database and the program code that drives me absolutely bonkers. I hope I'm not the only one to think this, but it bothers me that I have to create statements like the following

```<code>string sSql =  "SELECT * from tablename"
</code>```

When there's really no reason for that kind of unchecked language binding between two languages and two API's. Don't get my wrong, SQL is great, but I don't like the idea that, when executing commands on a SQL database, that one must intermix database and application software, and there's no database independence, which means that different versions of different databases can break code. This isn't very nice.

The nicest thing about Foxpro is the cohesiveness between programming language and database. It's so easy, and Foxpro makes it easy, because the tool just fits the task. I can see why so many developers have created a career with this language, because it lowered the barrier of entry to data-driven applications that so many businesses need. It was wonderful.

For my purposes today, with the demands and need for community support, extensibility, and language features, Foxpro isn't a solution that I feel would be the right tool for the job.

I'm also worried about working too heavy with the database, because I've seen data-driven .NET applications have issues with database caches, running out of memory, and objects in the database not being collected. (Memory leaks)

And OH the queries.

Which one, how, and why?

There are a plethora of different ways that a database can be setup, I think I counted 5 or 6 different kinds of database applications alone that I can chose from. That is a great mountain for me to climb when I don't even know where to begin when it comes to writing data-driven applications.

The problem isn't that I don't know SQL or that I don't know C#. I know both and have worked with both extensively. It's making them work together that's the problem, and it's something I've never done in C# before.

Reports

The client likes paper. The data needs to be printed out in a format that is extensible, layered, and easy to use. I have never done reporting before, and so this is a bit of a problem. From the data source comes crystal reports, and so there's a dependency on the database, from what I understand.

Code reuse

A large part of the design decision that I've gone through so far is to break the task of writing a piece of this software into routines and modular DLL's and so forth such that much of the code can be reused.

For example, when I setup this database, I want to be able to reuse the same database code over and over again.

I also want to make sure that when the day comes that another developer is here, that he/she will be able to pick up just where I left off.

The quicker I develop these applications, the better off I am.

Tasks & Goals

In my project, I need to write routines that apply algorithms and look for predefined patterns in financial data. Additionally, I need to simulate trading based on predefined algorithms and data. Then I need to prepare reports on that data.

Additionally, I need to have a way to change the code base for this application quickly and effectively, without hacking together some band-aid solution for a problem that really needs a trauma ward.

Special Considerations

The solution must be fast, run quickly on existing hardware, and not be too much of a pain to maintain and write. I understand that anything I write I'm married to -- I'm responsible for the things that I write because my reputation and livelihood is dependent on it.

Do I really need a database?

What about performance? Performance was such a big issue that I hand wrote a data structure that is capable of performing 2 billion operations, using a total of 4 gigs of memory in under 1/4 of a second using the standard core two duo processor. I could not find a similar, pre-written data structure in C# to perform this task.

What setup do I use in terms of database?

What about reporting? I'd prefer to have PDF's generated, but I'd like to be able to visually sketch those reports and then just have a ReportFactory of some sort, that when I pass some variables in, it just does that data.

About Me

I'm a lone developer for a small business in this area. This is the first time I've done this and I've never had the breadth and depth of my knowledge tested.

I'm incredibly frustrated with this project because I feel incredibly overwhelmed with the task at hand.

I'm looking for that entry level point where I can draw a line and say "this is what I need to do"

 Conclusion

I may have not been clear enough on my post. I'm still new to this whole thing, and I've been doing my best to contribute back to the community that I've leached so much knowledge from. I'd be glad to edit my post and add more information if possible.

I'm looking for a big-picture solution or design process that helps me get off the ground in this world of data-driven applications, because I have a feeling that it's going to be concentric to my entire career as a programmer for some time.

Specifically, if you didn't get it from the rest of the post (I may not have been clear enough) I really need some guidance as to where to go in terms of the design decisions for this project. Some things that'll be useful will be a pro/con list for the different kinds of database projects available in VS2010. I've tried, but generating that list has been as hard as solving the problem itself...

If you could walk a developer writing a data-driven application for the first time in C#, how would you do that? Where would you point them to?

答:
Phew! That's a hum-dinger of a question.

One suggestion I'd make is that, should you decide to move to Microsoft SQL Server as your database, then you should really consider using the SO-used library called Dapper.

It's a really easy-to-use interface between C# code and SQL Server, and should at least address your statement:

It's that bridge between the database and the program code that drives me absolutely bonkers.


问:
Algorithm to calculate trajectories from vector field
I have a two-dimensional vector field, i.e., for each point (x, y) I have a vector (u, v), whereas u and v are functions of x and y.

This vector field canonically defines a set of trajectories, i.e. a set of paths a particle would take if it follows along the vector field. In the following image, the vector field is depicted in red, and there are four trajectories which are partly visible, depicted in dark red:

I need an algorithm which efficiently calculates some trajectories for a given vector field. The trajectories must satisfy some kind of minimum denseness in the plane (for every point in the plane we must have a 'nearby' trajectory), or some other condition to get a reasonable set of trajectories.

I could not find anything useful on Google on this, and Stackexchange doesn't seem to handle the topic either.

Before I start devising such an algorithm by myself: Are there any known algorithms for this problem? What is their name, for which keywords do I have to search?

答:
Naive algorithm, that is based on numerical methods (like nilu says):

Take starting point as current point

Calculate vector based on closest vectors in field and weighted based on distance of current point to them

Calculate new point based on current point, calculated vector and some epsilon, that states length of step

Repeat 2 and 3 to get list of points of your trajectory

Step 2. would be trickiest. First thing that comes to mind is to use same kind of weighted distance math, that is used in perlin noise. It would probably need some fine-tuning to get results with acceptable error. But you can only do "this much" with low-density field.


答:
I also learnt object-oriented programming coming from procedural programming (Pascal and C) so I can understand the difficulty of the switch: you have to start thinking differently, and you already have a lot of experience in another paradigm (BTW, I still enjoy programming in the procedural way from time to time).

Besides reading language-specific books, I think it would be useful to read a general introduction to object-orientation and object-oriented design.

For example, I found Object-Oriented Modelling and Design very useful. The book is not very recent, but the basic concepts of object orientation have not changed that much. Also, I like this book because it concentrates on design concepts and only in the later chapters it explains how to map these concepts to programming language constructs. Furthermore, it shows that an object-oriented design can (also) be implemented in non-object oriented languages (e.g. C) if you need to.

So, in addition to books specific to Objective-C, I would recommend such a language-agnostic reading to get general ideas that are not biased by a particular object-oriented language.

Title: Learning OO for a C Programmer

Body:
I've been programming professionally in C, and only C, for around 10 years in a variety of roles.

As would be normal to expect, I understand the idioms of the language fairly well and beyond that also some of the design nuances - which APIs to make public, who calls what, who does what, what is supposed to reentrant and so on. I grew up reading 'Writing Solid Code', it's early C edition, not the one based on C++.

However, I've never ever programmed in an OO language. Now, I want to migrate to writing applications for iPhone (maybe android), so want to learn to use Objective-C and use it with a degree of competence fitting a professional programmer.

How do I wrap my head around the OO stuff? What would be your smallest reading list suggestion to me.

Is there a book that carries some sort of relatively real world example OO design Objective-C?

Besides, the reading what source code would you recommend me to go through.

How to learn OO paradigm using Objective-C?


答:
Oddly I would suggest "Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques" by Damion Conway.

I would then use Ruby to write some OO programs.

The SICP also has a section of OO programming.

Learning object oriented programming is is different than learning C++.  You can write very nice functional programming in C++ and you could write an OO program in C.  So you have 2 things you need to learn C++ and OO programming.

Title: Learning OO for a C Programmer


问:
Can You Have "Empty" Abstract/Classes?
Of course you can, I'm just wondering if it's rational to design in such a way.

I'm making a breakout clone and was doing some class design. I wanted to use inheritance, even though I don't have to, to apply what I've learned in C++. I was thinking about class design and came up with something like this:

GameObject -> base class (consists of data members like x and y offsets, and a vector of SDL_Surface*

MovableObject : GameObject -> abstract class + derived class of GameObject (one method void move() = 0; )

NonMovableObject : GameObject -> empty class...no methods or data members other than constructor and destructor(at least for now?).

Later I was planning to derive a class from NonMovableObject, like Tileset : NonMovableObject. I was just wondering if "empty" abstract classes or just empty classes are often used...I notice that the way I'm doing this, I'm just creating the class NonMovableObject just for sake of categorization.

I know I'm overthinking things just to make a breakout clone, but my focus is less on the game and more on using inheritance and designing some sort of game framework.

答:
You are not over thinking it; you are thinking and that is good.

As already stated, don't use a language feature just because it's there. Learning language feature tradeoffs are key to good design.

One should not use base classes for categorization. That could implicate checking type. That is a bad idea.

Consider writing pure abstractions that define your objects' contract. Your objects' contract is the outward facing interface. Its public interface. What it does.

Note: It is important to understand this is not what data it has x, y but what it does move().

In your design, you have a class GameObject. You are relying on it for its data and not its functionality. It feels efficent and correct to use inheritance for sharing what seems like common shared data, in your case x and y.

This is not the correct use of inheritance. Always remember, inheritance is the tightest form of coupling you can possibly have and you should strive for loose coupling at all times.

By its very nature NonMovableObject doesn't move. Its x and y should most certainly be declared const. By its very nature MoveableObject needs to move. It cannot declare its x and y as const. Thus, this is not the same data and it cannot be shared.

Consider your objects' functionality, or contract. What should they do? Get that right and the data will come. Work on one object at a time. Worry about each in turn. You will find your good designs are reusable.

Perhaps there isn't a NonMovableObject at all. What about a pure abstraction GameObjectBase that defines a move() method? Your system instanciates GameObjects which implement move() and the system only moves the ones that need to move.

This is just the beginning; a taste. The rabbit hole goes much deeper. There is no spoon.

Title: Can You Have "Empty" Abstract/Classes?


答:
You should catch general exceptions at the top level of every process, and handle
it by reporting the bug as well as possible and then terminating the process.

You should not catch general exceptions and try to continue execution.


问:
How to better start learning programming - with imperative or declarative languages?
Someone is interested in learning to program. What language paradigm should I recomend him - imperative or declarative? And what programming language should he start with?

I think that declarative because it is closer to math. And I would say that Prolog might be the best start because it is based on logic and programs are short. On the other hand at school we started learning from imperative languages and I am not sure whether there is a benefit to start with them instead of declarive ones.

Thanks. :)

答:
I taught myself Commodore Structured Bsic, then learned Waterloo Structured Basic and Fortran in high school, and found it so easy. Then I taught myself Prolog, and while I hated the debugging and learning curve (after being taught purely imperative methods), I eventually learned it and to this day, it remains my favourite language. Not that I get hardly any chances to use it, but it teaches you to really think about the application at hand, and break down the work, as opposed to sloppily diving in and nibbling away at the task procedurally.

Nowadays I use various imperative languages, and miss Prolog's elegance, but the lessons I learned were never lost. Anyone can pick up imperative languages, but learning them first makes it harder to learn declarative languages afterwards. Learning declarative languages first teaches good concepts for life, and saves grief trying to get your head around it after learning imperative languages.

If you will only ever write simple scripts or apps with highly deliberate routines that you can easily figure out, then you may as well skip declarative languages, but if you may ever tackle something far too big for any single human brain, you will bless the days you learned the techniques in attacking a project using a declarative language. And why limit yourself from day one to simple coding that one day will surely be done by an app or offshored for a fraction of your price? I say it's truly worth the short 'pain'.

So I vote for learning a declarative language in school, then a more popular imperative language, which is the best way to instill good planning behaviour while minimizing the learning curve.


答:
Step 1: classes are structs with functions. Mixing data with functions is useful.

Step 2: In a class you limit the visibility of functions and variables. Usually you will have a few public functions that are the "interface" of the class. The advantage of hiding things is you can change them without the user's of your class needing to change. As long as you preserve the public interface you are good to go. It also makes it easier for people to use your class as they won't get confused trying to understand the private details and can focus on the public interface.

Step 3: You can inherit fields and functions from a parent class. This can help prevent some duplication between different sub-types. You can also override the functionality of inherited functions if you choose.  Inheritance is one of the least useful features of OOP but there it is.

Step 4: Polymorphism lets you create "pluggable" software. To add functionality you make a new class that satisfies an interface with it's functions. You create the class and it sort of plugs in. You do not make any changes to the work-flow code. Without OOP you would have lots of "if-elseif-elseif" statements in your work-flow to perform different actions for different things.  With OOP those if statements disappear because you call the method of your object. Your object's function does what it needs to do polymorphically.

For example you have a class "Engine". It has children "DirectXEngine", "OpenGLEngine". Your game works fine for years.  Then 5 years later someone events a new engine and you want to support it in your game. You create a class "SomeNewEngine" and it plugs into your video game. You fully support the new engine without any changes to the workflow code.  All you had to do was make a new class. All you have to test (in theory) is that your new class's functions satisfy the interface. (but in reality it is not always feasible to conform things to the same interface...)

Step 5:  Understanding polymorphism is not limited to OOP. You can get polymorphic behavior from generic programming. Consider an "add" function

```<code>T add(T val1, T val2) {
    return val1 + val2;
}
</code>```

It works whether you pass in floats, ints, doubles, strings, etc. Even though the implementation of adding these types is very different. This is polymorphism on the source code level. If you think of the "+" operator as a behavior that all the types support, then they all conform the the "+" interface.

You can conceptualize all behavior as functions. Whether it's an actual function or a syntax of the language like +, -, %, etc.

Take it a step further and you remove all syntax from the language. You are now at the point every function you create "is" the language. You create your own language as you program in your language. You support all programming paradigms but are no paradigm. OOP becomes an irrelevant definition of a few techniques that are part of the natural world.

Title: Learning OO for a C Programmer

Body:
Step 1: classes are structs with functions. Mixing data with functions is useful.

Step 2: In a class you limit the visibility of functions and variables. Usually you will have a few public functions that are the "interface" of the class. The advantage of hiding things is you can change them without the user's of your class needing to change. As long as you preserve the public interface you are good to go. It also makes it easier for people to use your class as they won't get confused trying to understand the private details and can focus on the public interface.

Step 3: You can inherit fields and functions from a parent class. This can help prevent some duplication between different sub-types. You can also override the functionality of inherited functions if you choose.  Inheritance is one of the least useful features of OOP but there it is.

Step 4: Polymorphism lets you create "pluggable" software. To add functionality you make a new class that satisfies an interface with it's functions. You create the class and it sort of plugs in. You do not make any changes to the work-flow code. Without OOP you would have lots of "if-elseif-elseif" statements in your work-flow to perform different actions for different things.  With OOP those if statements disappear because you call the method of your object. Your object's function does what it needs to do polymorphically.

For example you have a class "Engine". It has children "DirectXEngine", "OpenGLEngine". Your game works fine for years.  Then 5 years later someone events a new engine and you want to support it in your game. You create a class "SomeNewEngine" and it plugs into your video game. You fully support the new engine without any changes to the workflow code.  All you had to do was make a new class. All you have to test (in theory) is that your new class's functions satisfy the interface. (but in reality it is not always feasible to conform things to the same interface...)

Step 5:  Understanding polymorphism is not limited to OOP. You can get polymorphic behavior from generic programming. Consider an "add" function

T add(T val1, T val2) {
    return val1 + val2;
}

It works whether you pass in floats, ints, doubles, strings, etc. Even though the implementation of adding these types is very different. This is polymorphism on the source code level. If you think of the "+" operator as a behavior that all the types support, then they all conform the the "+" interface.

You can conceptualize all behavior as functions. Whether it's an actual function or a syntax of the language like +, -, %, etc.

Take it a step further and you remove all syntax from the language. You are now at the point every function you create "is" the language. You create your own language as you program in your language. You support all programming paradigms but are no paradigm. OOP becomes an irrelevant definition of a few techniques that are part of the natural world.


问:
One page using querystring or many folders and pages?
I have an application where I have the 'core' code in one folder for which there is a virtual directory in the root, such that I can include any core files using /myApp/core/bla.asp. I then have two folders outside of this with a default.asp which currently use the querystring to define what page should be displayed. One page is for general users, the other will only be accessible to users who have permission to manage users / usergroups / permissions. The core code checks the querystring and then checks the permissions for that user. An example of this as it is now is default.asp?action=view&viewtype=list&objectid=server. I am not worried about SEO as this is an internal app and uses Windows Auth.

My question is, is it better the way it is now or would it be better to have something like the following:

/server/view/list/

/server/view/?id=123

/server/create/

/server/edit/?id=123

/server/remove/?id=123

In the above folders I would have a home page which defines all the variables which are currently determined by the querystring - in /server/create/ for example, I would define the action as 'create', object name as 'server' and so on.

In terms of future development, I really have no idea which method would be best. I think the 2nd method would be best in terms of following what page does what but this is such a huge change to make at this stage that I would really like some opinions, preferably based on experience.

PS Sorry if the tags are wrong - I am new to this forum and thought this was a bit too much of a discussion for StackOverflow as that is very much right / wrong answer based. I got the idea SE is more discussion based.

答:
The best way is to split it up. This will make it much easier to maintain because there are only small chunks that you need to deal with at any one time.

What you need to do is to first create a framework which will be used universally across all the pages/functions. This will have common bits in it like access control, menus, validation scripts, styles, etc

Then are there any objects that could be shared across pages? Things like business objects, data access layers, report generation, drop downs, etc. Put these into separate classes/files/etc. If you need to code it more than once, it should be in a library type file and included where required.

Now build pages for each discrete action, and group them by functionality or by permissions into separate folders.

Remember that a query string is an easy way for a user to enter in false data - does the application require a level of robustness? Best way is to use a session type object for passing information between pages for a security and integrity point of view.


问:
What is better for coding - desktop or laptop?
Use of desktops are decreasing day by day in daily life but for coding purpose are there any reasons for using desktop over laptop? </p>

答: I'd go for laptops with external monitors. It's perfect for situations where you get tired of coding on your desk and you want to go somewhere else to code. You can also take it with you around the office in case you want to show or discuss your code with your officemates personally while not having them go all the way to your far away desk.</p>


答:
Thanks for your question! Full disclaimer, I work on the Dart team.

Probably the best advantage Dart has today is that it's familiar to C#, Java, C++, and most JavaScript developers. Many developers have a set of expectations around their language (class-based OO, lexical scope, familiar syntax) and their tools (code completion, refactoring, code navigation, debugging) that Dart aims to meet and exceed.

Here's some things that I like about the language:

Optional static types. When I'm prototyping or simply writing small scripts, I don't use a ton of static types. I just don't need 'em, and I don't want to get bogged down with the ceremony. However, some of those scripts evolve into bigger programs. As the scripts scale, I tend to want classes and static type annotations.

Innocent until proven guilty. Dart tries hard to minimize the situations that result in a compile-time error. Many conditions in Dart are warnings, which don't stop your program from running. Why? In keeping with web development fashion, it's imperative to allow developers to try a bit of code, hit reload, and see what happens. The developer shouldn't have to first prove the entire program is correct before just testing a corner of the code.

Lexical scope. This is awesome, if you're not used to it. Simply put, the visibility of variables, and even this, is defined by the program structure. This eliminates a class of puzzlers in traditional web programming. No need to re-bind functions to keep this to what you think or expect.

Real classes baked into the language. It's clear most developers want to work in classes, as most web development frameworks offer a solution. However, a "class" from framework A isn't compatible with framework B, in traditional web development. Dart uses classes naturally.

Top-level functions. One painful part of Java is that everything has to be put into a class. This is a bit artificial, especially when you want to define a few utility functions. In Dart, you can define functions at the top level, outside of any class. This makes library composition feel more natural.

Classes have implicit interfaces. The elimination of explicit interfaces simplifies the language. No more need to define IDuck everywhere, all you need now is a class Duck. Because every class has an implicit interface, you can create a MockDuck implements Duck

Named constructors. You can give constructors names, which really helps with readibility. For example: var duck = new Duck.fromJson(someJsonString)

Factory constructors. The factory pattern is quite common, and it's nice to see this baked into the language. A factory constructor can return a singleton, an object from a cache, or an object of a sub-type.

Isolates. Gone are the days of sharing mutable state between threads (an error prone technique). A Dart isolate is an isolated memory heap, able to run in a separate process or thread. Isolates communicate by sending messages over ports. Isolates work in the Dart VM and can compile to Web workers in HTML5 apps.

Dart compiles to JavaScript. This is critically important, as JavaScript is the lingua franca of the web. Dart apps should run across the modern web.

Strong tooling. The Dart project also ships an editor. You'll find code completion, refactoring, quick fixes, code navigation, debugging, and more. Also, IntelliJ has a Dart plugin.

Libraries. You can organize Dart code into libraries, for easier namespacing and reusability. Your code can import a library, and libraries can re-export.

String interpolation. This is just a nice feature, making it easy to compose a string: var msg = "Hello $friend!";

noSuchMethod Dart is a dynamic language, and you can handle arbitrary method calls with noSuchMethod().

Generics. Being able to say "this is a list of apples" gives your tools much more info to help you and catch potential errors early. Luckily, though, Dart's generics are more simple that what you're probably used to.

Operator overloading. Dart classes can define behavior for operators like + or -. For example, you could write code like new Point(1,1) + new Point(2,2).

Having said all that, there are many more JavaScript libraries out there.

Personally, I believe there's room on the web for many languages. If the app is awesome, and it runs in the majority of modern browsers, I don't care as much what language it is written in. As long as you, the developer, are happy, productive, and launching on the web, that's what matters! :)

Title: Does Dart have any useful features for web programmers?

Body:
http://www.dartlang.org/

I've checked out the site very briefly, and got curious. Is there any advantages of using Dart? Is it just a replacement for JavaScript?

It looks like simpler Java. Writing quite a lot of C# at work, the language feels very much like what I'm used to, so learning the syntax looks like a breeze to learn. Has anybody any opinions or experiences with the language?

(Compared to CoffeeScript (= I'm not doing Ruby syntax) the syntax looks more familiar to me).


答:
Copy Apple as much as you can. Apple's Objective-C APIs for iOS are clearly written, very consistent, and make good use of a number of OO design patterns. Apple also has some great sample code that usually demonstrates the idiomatic iOS way of doing things. Just be cautious and check the dates on any sample code you download. Some of the older sample projects use outdated paradigms.

Doing this isn't going to give you a grand overview of writing OO code, but if your goal is to port your projects to iOS, this will give you a great start in writing good, clean iOS code.

Title: Learning OO for a C Programmer


答:
For me, it gives me the chance to structure my code better than JavaScript with scope and classes.

It's similar to Java and JavaScript and with Dart editor, I had close to zero adaptation. I started coding straight away.

var ws = new [Moz]WebSocket having to cater for different browsers is annoying. Dart compiles to JavaScript code compatible with popular browsers.

My challenge mainly is interfacing with JavaScript code. I somehow  find ways around it but it would be better if it's part of Dart.


问:
What's the equivalent name of "procedure" in OOP?
In several of my programming courses in the University, my teachers always told me the following:

A function and a procedure are basically the same thing: the only difference is that a function returns a value, and the procedure doesn't.

That means that this:

```<code>function sum($a, $b) {
    return $a + $b;
}
</code>```

... is a function, and this:

```<code>function sum($a, $b) {
    echo $a + $b;
}
</code>```

... is a procedure.

In the same train of thought, I've seen that a method is the equivalent of a function in the OOP world.

That means that this:

```<code>class Example {
    function sum($a, $b) {
        return $a + $b;
    }
}
</code>```

Is a method — but how do you call this?

```<code>class Example {
    function sum($a, $b) {
        echo $a + $b;
    }
}
</code>```

What's the equivalent name, or how do you call a method that doesn't returns anything?

答: Method as a concept encompasses both the function and procedure notations.


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答: I will go with design first then code concurrently. It is very important because every projects are different. You need to come out with a plan and high level of process workflow from A to Z before you can start working on the codes concurrently. Every decision made are to be documented so other teams (or yourself) who are/is developing the codes will know the latest update and what has been confirmed.</p>


答:
Objective-C is a cleanly written language with a good API. It also has an innovative design and implementation methodology, but it suffers from many C limitations that C++ vastly improved on or added completely out of thin air.

Notable examples of this are:

Generics/Template meta programming

Safer Casts

Both stack and heap allocation - NOTE: this isn't something that C lacks technically, but Objective-c does - where as C++ has this feature. In a nutshell, it only allows heap allocation for objects, where as primitive types are usually stack allocated. You can do stack allocation with C-style structs, but that's your limitation (and you forgo the main benefits of OOP, for the most part - so, you may as well just write in C if you take that route - however, you can embed your Objective-C code into C style code)

Differentiation between public, private, and protected method inheritance/virtualization.

The ability to pass purely by and receive by references.

Smart Pointers to assist with memory management.

Built in constructors and destructors which are enforced by more than just standards.

Many more APIs and libraries than what exist in the Objective-C/iOS world.

If your focus is more on learning iOS as opposed to just OOP, then Objective-C is the best choice you could really make. Granted, keep in mind that this will have you focusing on more GUI-centric things (such as event-driven programming), which may or may not be what you want to begin with. There's also the down side of the fact that iOS and Objective-C, while going hand in hand, really are only good for each other and not meant for anything else outside of that (in terms of an application building perspective).

If you want to learn about OOP from a more general perspective, and apply what you've learned to something more generic and well-rounded (in the sense that you can take it pretty much anywhere you go), I'd recommend learning either C++ or Java. Java is entirely different, semantically, than C, however it does have many features within it that C++ has.

You're not going to have as much control over your program, but if you need to you can use the JNI (Java Native Interface) to write Java code that can be sent to both C and C++ code.

Either way, regardless of what language/platform/environment you choose, someone with your skills shouldn't have a tough time at least getting the basics down and running with that. It may take a bit for everything to really sink in though, due to the fact that you've been writing procedurally for so long.

My two cents.

Title: Learning OO for a C Programmer


答: Imperative programming distinguishes value-returning blocks from merely code-executing blocks via names: function and procedure. OOP doesn't; as Jesse explained, both are called methods. This is one of the major problems in moving between programming (and, in fact, natural) languages: not only do they use different terms for the same things, they don't even agree about which things count as "the same" and which don't.

Title: What's the equivalent name of "procedure" in OOP?

Body:
In several of my programming courses in the University, my teachers always told me the following:

A function and a procedure are basically the same thing: the only difference is that a function returns a value, and the procedure doesn't.

That means that this:

```<code>function sum($a, $b) {
    return $a + $b;
}
</code>```

... is a function, and this:

```<code>function sum($a, $b) {
    echo $a + $b;
}
</code>```

... is a procedure.

In the same train of thought, I've seen that a method is the equivalent of a function in the OOP world.

That means that this:

```<code>class Example {
    function sum($a, $b) {
        return $a + $b;
    }
}
</code>```

Is a method — but how do you call this?

```<code>class Example {
    function sum($a, $b) {
        echo $a + $b;
    }
}
</code>```

What's the equivalent name, or how do you call a method that doesn't returns anything?


答:
I'd suggest you start with exploring the new options that the language provides. At first they seemed a bit useless for me, but with the time everything goes to its place. For this purpose I used cplusplus.com and cprogramming.com
Having covered (or refreshed) the basics you need to introduce yourself with some C++ philosophies, which are very different from C. For example:

use const or inline instead of macross

use new/delete instead of malloc/free

best practices when dealing with exceptions/constructors/etc
For this purpose I recommend Effective C++: http://www.amazon.com/Effective-Specific-Improve-Programs-Designs/dp/0321334876

Beyond this point I think it's best to find a C++ project to work on. With the real work you'll solve real problems and gain experience, which as you already know is invaluable. Good luck :)

Title: Learning OO for a C Programmer


问:
How to learn to make better estimates?
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).

答:
Rather than write a book on it, I'll just offer a little advice on how to use the "break down" method of estimation:

Break your assignment down into smaller component tasks.  Estimate each task as best as possible.

Add a task for planning and design (which includes what you're doing now.)  Estimate it.

If you don't already have one, add a task for "bringing the tasks together."  This task may not seem useful at first.  However, when you use this "break down" method of estimation, there are always time consuming things to do that "fall between tasks" and that "pull the tasks together."  This one can be tricky to estimate.  Try your best.

Add a task for testing and documentation.  Your assignment may not require a lot of testing and documentation, but you should at least spend a little time thinking about it.

Add up the task estimates to get an overall estimate.

Go ahead and multiply that total estimate by two††.  This will give you padding time to:

Finish things that you overlooked in your original task list

Finish things that you couldn't have known about until getting under way

Incorporate feedback from other people, and make changes

Get interrupted by other things going on around you, like meetings

Finish ahead of estimate more often than behind it

And last, but not least, don't be afraid to sketch out estimates for yourself that are probably totally wrong.  Sometimes just sketching everything out, no matter how potentially wildly inaccurate, can help you start on the path to getting a better sense for what's involved.

††As you get more and more experience, this "fudge factor" can be tuned to suit your personal style, and your work environment.

Title: How to learn to make better estimates?