答:
TL;DR answer:

The Runtime Envionment is a somewhat nebulous term which collectively refers to the virtual machine in which your code runs, and the standard libraries and services that your code may expect to find available to it.  It can also be thought of as a layer of isolation between your code and the underlying operating system, so that your code can be agnostic of it, and therefore portable.

The long answer:

In the (not so good) old days when FORTRAN and COBOL ruled, the language was also the Runtime Environment.  Most applications were built using whatever features the language provided, and that was enough.  As a result, the syntax of the languages was very complex, and still the stuff that you could do with them were limited to whatever the authors of the language could imagine at the time that they were creating the language: accessing files and databases, reading and writing characters to and from terminals, and that was pretty much it.

When C came out, it made a clear distinction between the language and the Runtime Libraries.  The C language itself is extremely minimalistic, offering only the bare essentials necessary for expressing program logic, and delegating everything else to be done by libraries. The standard libraries provide commonly used stuff, and you can add external libraries for anything else.

For example, the C language has no built-in concept of memory allocation; in order to allocate memory you have to invoke malloc(), a standard library routine. And if malloc() is not good enough for you, then you can use some other library that offers something that better suits your needs. The standard runtime libraries were the precursor of runtime environments, but things were not really there yet, because back in the days of C the Unix operating system was mostly playing the role of the runtime environment, so there was no concept of portability: according to the Unix world, the Unix world was the only world.

When the portable, virtual-machine-based languages like Java and C# came out, there was a need to provide an additional layer of isolation between applications and the underlying operating system, so that applications could run either on Unix, or on Windows, or on anything else. That was provided by the virtual machine and the rich set of libraries that it came with.

Title: What really is the "runtime environment"?

Body:
This is a very basic question but is something I've never completely understood and recently, when studying .NET Core and ASP.NET 5 I felt the need of a more complete understanding of the topic.

Reading the article Introduction to the Common Language Runtime (CLR) there we find the following piece of text:

Every program has a surprising number of dependencies on its runtime environment. Most obviously, the program is written in a particular programming language, but that is only the first of many assumptions a programmer weaves into the program. All interesting programs need some runtime library that allows them to interact with the other resources of the machine (such as user input, disk files, network communications, etc). The program also needs to be converted in some way (either by interpretation or compilation) to a form that the native hardware can execute directly.

Now, this idea of runtime environment seems to be very basic, but still very important, not just when working with .NET but when dealing with programming in general. It seems to be a general concept which is quite important to understand.

Until today I always had one intuitive and simple understanding about it: runtime environment is the environment on which the code will run. But this is a quite loose way to understand it. There is probably much more to it as can be infered from the above text.

In that setting: what really is the runtime environment in general? Not just for .NET, but in programming in general, what is the runtime environment? Is it just something conceptual or is it some piece of software, like the CLR for .NET? In summary, how should we properly understand the idea of runtime environment?

ContentLicense: CC BY-SA 4.0


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答: Juggling while having a break

OwnerDisplayName: Nick Gotch

ContentLicense: CC BY-SA 2.5

Title: How to become a "faster" programmer?

Body: Juggling while having a break

OwnerDisplayName: Cornelius


问:
What really is the "runtime environment"?
This is a very basic question but is something I've never completely understood and recently, when studying .NET Core and ASP.NET 5 I felt the need of a more complete understanding of the topic.

Reading the article Introduction to the Common Language Runtime (CLR) there we find the following piece of text:

Every program has a surprising number of dependencies on its runtime environment. Most obviously, the program is written in a particular programming language, but that is only the first of many assumptions a programmer weaves into the program. All interesting programs need some runtime library that allows them to interact with the other resources of the machine (such as user input, disk files, network communications, etc). The program also needs to be converted in some way (either by interpretation or compilation) to a form that the native hardware can execute directly.

Now, this idea of runtime environment seems to be very basic, but still very important, not just when working with .NET but when dealing with programming in general. It seems to be a general concept which is quite important to understand.

Until today I always had one intuitive and simple understanding about it: runtime environment is the environment on which the code will run. But this is a quite loose way to understand it. There is probably much more to it as can be infered from the above text.

In that setting: what really is the runtime environment in general? Not just for .NET, but in programming in general, what is the runtime environment? Is it just something conceptual or is it some piece of software, like the CLR for .NET? In summary, how should we properly understand the idea of runtime environment?

答:
There are a few components that make up the runtime environment. Not all components are applicable to all environments (e.g. assembler, C++, and C# all have different runtime facilities), but they generally comprise the following:

The CPU and hardware platform on which the program runs.

The operating system that runs the program, including device drivers that interface with the hardware.

Standard libraries available to the language and platform. Certain environments (e.g. embedded) may pare down the relevant standard library due to space concerns.

Frameworks and other libraries linked into the program either statically or dynamically.

Any interpreter that sits between the program and the operating system, such as the CLR, JVM, shell (for e.g. a Bash script), Perl/Python interpreter, et al.

Remember, computers are all about layers and abstractions. As you can gather from the list above, a runtime is pretty much a collection of abstractions that sit between the bare metal and the running program.

ContentLicense: CC BY-SA 3.0


答: Drinkng Yerba Mate instead of Coffee

Title: How to become a "faster" programmer?

Body:
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

Body: Drinkng Yerba Mate instead of Coffee


问:
Class design dilemma: Encapsulation vs Single Responsibility/Separation of Concerns
I'm working on a class that represents an object with multiple representations - one is an XML type representation used by an automatic ordering system, the other is a POJO-based representation used by a monitoring tool.

The problem I'm running into is that I seem to have to make trade-off between encapsulating the object's internal data and designing my application according to the principle of "separation of concerns" or "single responsibily per class".

Let's look at the class in more detail:

```<code>public class MyObject {
    private Object field1;
    private Object field2;
    private Object field3;
    ...
    private Object field100;
}
</code>```

(Yes it's quite a big ugly monster, something I have no control over).

If I follow the principle of separation of concerns (the way I understand it anyway), I will have to add getters for every field in this class and have a separate XMLBuilder class for the XML representation, and a PojoBuilder for the Monitoring tool representation:

```<code>public class XMLBuilder {

    public XML asXml(MyObject obj) {
        return "<tag1>" + object.getField1() + "</tag1>"
               "<tag2>" + object.getField2() + "</tag2>"
               ...
               ;
        }
}
</code>```

This seems to me to break the principle of encapsulation - I have to expose a lot of the internal data on my class just to provide a representation for it. If I pass my object to other systems, I have no control whether these sub-systems may become dependent on arbitrary fields (i.e. field45), which means that future changes to the structure of this object may become difficult as there are now other possible dependencies on it.

An alternative approach, advocated by Allen Holub (http://www.javaworld.com/article/2073723/core-java/why-getter-and-setter-methods-are-evil.html) for example, is to do the representation inside the class:

```<code>public class MyObject {

    ...

    public XML asXml() {
        return "<tag1>" + field1 + "</tag1>"
               "<tag2>" + field2 + "</tag2>"
               ...
               ;
    }

    public Object asMonitor() {
        ...
    }

 }
</code>```

To me, this solution seems great, as the class never exposes any private fields. The representation generators have access to all the information it needs, and the object itself can be safely passed to other sub-systems without the worry that another module would depend on internals.

Now, when I implement this, my colleagues all raise the issue of "Separation of concerns". The problem, they say, is that the MyObject class now have knowledge of things like XML representations and POJO represantions, which means that if the XML representation changes, you now have to make modifications inside the actual class itself, instead of just updating an "XML ruleset" or some other external configuration.

Holub's solution is to use a Builder pattern:

```<code>public class MyObject {

...

    public void buildContent(MyObjectBuilder builder) {
        builder.setField1(field1);
        builder.setField2(field2);
    }
 }

 public class XMLBuilder implements MyObjectBuilder {

     ...

     public void setField1(Object field1) {
         content += "<tag1>" + field1 + "</tag1>";
     }

     public XML asXML() {
         return content;
     }

     ...
 }
</code>```

but this seems hardly better than the first approach - instead of exposing data as getters, it is now implicitly exposed via a builder. OK, I understand that with the builder I may have additional control over how my object represents itself, but is that iota of control worth the increased complexity in the code base? Changes to the structure of MyObject will still likely result in downstream dependencies requiring updates, so I'm not entirely sure if much have been gained here (except that there are technically no getters).

Is this a case where you simply have to choose your poison? Or is there a magical middle ground that reduces all these issues? What are the common strategies for dealing with this?

答:
Is this a case where you simply have to choose your poison?

Yes, basically.

One of software developer's job is risk management when it comes to change. And there is lots of theory about risk management. Generally, you should first identify risks. You already did that : change of object itself, change of XML, change of POJO, etc.. All of those are possible risks. Next step would be to identify what are probabilities of the occurring. You can get some idea from looking back at changes you had to do in the past, but only real experience can help you here. Then, you have to identify impact of each risk. You say that changes can propagate through the dependencies, so the more dependencies the risk affects, the more costly it is when it occurs. Taking all of this in, you should make a design that minimizes risks that have high probability and high cost.

I can't tell you right now, because the way you described your problem is way too generic. And different systems would encounter different risks at different probabilities and costs. For example, if XML is used as communication between your systems, then updating it's schema might not be a problem. But if it is used for persistence, then maintaining backwards compatibility is a must. Etc..

Only thing I can suggest is to get more experience. More experience will give you more ideas about possible risks and their properties and ways to design to avoid those risks.


问:
Why is %s better than + for concatenation?
I understand that we should use %s to concatenate a string rather than + in Python.

I could do any of:

```<code>hello = "hello"
world = "world"

print hello + " " + world
print "%s %s" % (hello, world)
print "{} {}".format(hello, world)
print ' '.join([hello, world])
</code>```

But why should I use anything other than the +? It's quicker to write concatenation with a simple +. Then if you look at the formatting string, you specify the types e.g. %s and %d and such. I understand it could be better to be explicit about the type.

But then I read that using + for concatenation should be avoided even though it's easier to type. Is there a clear reason that strings should be concatenated in one of those other ways?

答:
Readability. The format string syntax is more readable, as it separates style from the data. Also, in Python, %s syntax will automatically coerce any non str types to str; while concatenation only works with str, and you can't concatenate str with int.

Performance. In Python str is immutable, so the left and right string have to be copied into the new string for every pair of concatenation. If you concatenate four strings of length 10, you will be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters, instead of just 40 characters. And things gets quadratically worse as the number and size of the string increases. Java optimizes this case some of the times by transforming the series of concatenation to use StringBuilder, but CPython doesn't.

For some use cases, the logging library provide an API that uses format string to create the log entry string lazily (logging.info("blah: %s", 4)). This is great for improved performance if the logging library decided that the current log entry will be discarded by a log filter, so it doesn't need to format the string.


问:
Could this class be considered as a Factory class?
I've recently worked on a reusable network service class for a service-aggregator iOS app. This class should retry a failed request if it was caused by expired user token. Plus, this class will be used between multiple contractors, who will create the aggregated services.

Since the contractors might use different authentication methods, I create a interface / protocol for the class that will manage user's authentication. Here's a sample of my work (in Swift):

BaseNetworkService.swift

```<code>class BaseNetworkService {

/**
Request headers that will be used by this instance.
*/
internal var requestHeaders = ["Content-Type": "application/json"]

/**
Request GET method to `URL` with passed `parameters`. Will send success response
in `next` and failure in `error` event of returned `RACSignal` instance.
*/
internal func GET(URL: String, parameters: [String: AnyObject]) -> RACSignal {
    // method implementation here
}

// Rest of HTTP methods here

}
</code>```

AuthenticatedNetworkService.swift

```<code>class AuthenticatedNetworkService: BaseNetworkService {

/**
Used to retrieve authentication-related request headers
and refresh expired user token.
*/
private var authService: AuthenticationProtocol

init(authService: AuthenticationProtocol) {
    self.authService = authService
}

/**
Request GET method to `URL` with passed `parameters`. Will send success response
in `next` and failure in `error` event of returned `RACSignal` instance.

- note: If the request fails because of expired user token, this instance will
refresh current user token, and retry it once again.
*/
override func GET(URL: String, parameters: [String: AnyObject]) -> RACSignal {
    // method implementation here
}

// Rest of HTTP methods here
}
</code>```

AuthenticationProtocol.swift

```<code>protocol AuthenticationProtocol {

/**
Stores authentication header name in the `key`, and its value in its
corresponding `value`.
*/
internal var authenticationHeaders: [String: String] { get }

/**
Checks whether passed `error` caused by expired user token or not.
*/
func isErrorCausedByExpiredToken(error: NSError) -> Bool

/**
Refresh this instance's `authenticationHeaders`. It send `next:` event from
returned `RACSignal` if the process succeeds, and `error:` otherwise.
*/
func refreshAuthenticatioHeaders() -> RACSignal

}
</code>```

I was reading about Design Patterns while working on this, and created a Factory-like class for creating the AuthenticatedNetworkService for the aggregated services. Something around this:

```<code>class AuthenticatedNetworkServiceFactory {

/**
Returns network service for Pizza Delivery service.
*/
class func PizzaDeliveryNetworkService() -> AuthenticatedNetworkService {
    let authService = PizzaDeliveryAuthenticationService()
    return AuthenticatedNetworkService(authService: authService)
}

/**
Returns network service for Quick Laundry service.
*/
class func QuickLaundryNetworkService() -> AuthenticatedNetworkService {
    let authService = QuickLaundryAuthenticationService()
    return AuthenticatedNetworkService(authService: authService)
}

/**
Returns network service for Cab Finder service.
*/
class func CabFinderNetworkService() -> AuthenticatedNetworkService {
    let authService = CabFinderAuthenticationService()
    return AuthenticatedNetworkService(authService: authService)
}

}
</code>```

Yet, after revisiting the GoF book, I found that Factory pattern was meant to return subclasses instead of a the main class. Since I was returning the main class (AuthenticatedNetworkService), is the AuthenticatedNetworkServiceFactory could be considered as a Factory? Or was it just a Helper class?

答:
There is no clear answer to your question, because the definition of a factory is not cast in stone.

Many people consider a factory to be anything that creates something for you so that you don't have to new it yourself.  This is dumb in my opinion, but who am I to say that your factories are not true factories ?

The real benefits of using a factory come when:

The factory decides which particular subclass to instantiate (as Kilian Foth mentioned) so that you don't have to know the actual class of the object created.

The factory is an abstract class itself, so not only you don't have to know the actual class of the object created, but you don't even know the actual class of the factory that you are invoking.

So, according to these real benefits™ your factory is in fact a helper, but if you still go ahead and call it a factory I do not think anybody can blame you. By calling it a factory you are simply advertising the fact that "this thang instantiates stuff".


答:
I think that sketching out your idea on paper, remember that stuff, is a great way to flesh out some ideas.  As programmers, whether professional or hobbyists, we spend soooo much time staring at the screen, that having another outlet on which to put your ideas is good.  I find that scratching things out, drawing hasty lines linking ideas, circling things, underlining, etc. all add to the emphasis on an idea and can really help you sort out an idea much faster than attempting to structure it right off the bat or in some computer-aided form.

Another thing that helps is prototyping small parts.  Listened to a TED audio podcast last night where the speaker was discussing building small structures out of spaghetti sticks and marshmallow, apparently this is a pretty widely-used study to test social construction abilities of small groups...anyway, the groups that always did better, besides architects who understood reinforcement and building construction were children because they used a stream of constant feedback to get results.  I think you can also throw this into a programming idea where you see that doing little things and getting results is not only more productive but a lot more fun and useful than building some giant construct and then spending days debugging it....that's killed some of my "fun" ideas in the past for sure.

Title: How to become a "faster" programmer?

OwnerDisplayName: dscher


问:
Why take a String input instead of int input for a number?
I'm a beginner in Java and I have a question from the "Head First Java" book. In the book, the author creates a method that takes the number as String and then convert it into int. Why do I need to take the input as a string and convert it rather than directly take it as an int. Below is he screenshot that I'm talking about.

答:
To me, this example is highlighting a very important point:

Users cannot enter "Integer" values.

Nor Dates, Decimals, Floats or any other Data Type ...

... except good, old-fashioned Strings that just happen to look like values in other Data Types.

Once you accept that the user can only work in Strings and that your application works in proper Data Types, your mind will be in a very Good Place to overcome a huge number of potential run-time bugs when working with User input.

Always "format" values as you put them in front of the user and "un-format" values as you read them back.  Assume that everything supplied by the User is inherently tainted and needs to be validated and verified.  (e.g.  is "q" numeric?  How about "e"?  Different languages; different tolerances).


问:
Filtering foreach loops with a where condition vs continue guard clauses
I've seen some programmers use this:

```<code>foreach (var item in items)
{
    if (item.Field != null)
        continue;

    if (item.State != ItemStates.Deleted)
        continue;

    // code
}
</code>```

instead of where I'd normally use:

```<code>foreach (var item in items.Where(i => i.Field != null && i.State != ItemStates.Deleted))
{
    // code
}
</code>```

I've even seen a combination of both. I really like the readability with 'continue', especially with more complex conditions. Is there even a difference in performance? With a database query I'm assuming there would be. What about regular lists?

答:
Of course there is a difference in performance, .Where() results in a delegate call being made for every single item.  However, I would not worry at all about performance:

The clock cycles used in invoking a delegate are negligible compared to the clock cycles used by the rest of the code that iterates over the collection and checks the conditions.

The performance penalty of invoking a delegate is of the order of a few clock cycles, and luckily, we are long past the days when we had to worry about individual clock cycles.

If for some reason performance is really important for you at the clock cycle level, then use List<Item> instead of IList<Item>, so that the compiler can make use of direct (and inlinable) calls instead of virtual calls, and so that the iterator of List<T>, which is actually a struct, does not have to be boxed. But that's really trifling stuff.

A database query is a different situation, because there is (at least in theory) a possibility of sending the filter to the RDBMS, thus greatly improving performance: only matching rows will make the trip from the RDBMS to your program.  But for that I think you would have to use linq, I do not think this expression could be sent to the RDBMS as it is.

You will really see the benefits of if(x) continue; the moment you have to debug this code: Single-stepping over if()s and continues works nicely; single-stepping into the filtering delegate is a pain.


答:
I would regard this as an appropriate place to use command/query separation. For example:

```<code>// query
var validItems = items.Where(i => i.Field != null && i.State != ItemStates.Deleted);
// command
foreach (var item in validItems) {
    // do stuff
}
</code>```

This also allows you to give a good self-documenting name to the query result. It also helps you see opportunities for refactoring, because it's much easier to refactor code that only queries data or only mutates data than mixed code that tries to do both.

When debugging, you can break before foreach to quickly check whether the contents of validItems resolve to what you expect. You don't have to step into the lambda unless you need to. If you do need to step into the lambda, then I suggest factoring it out into a separate function, then step through that instead.

Is there a difference in performance? If the query is backed by a database, then the LINQ version has the potential to run faster, because the SQL query may be more efficient. If it's LINQ to Objects, then you won't see any real performance difference. As always, profile your code and fix the bottlenecks that are actually reported, rather than trying to predict optimisations in advance.

Title: Filtering foreach loops with a where condition vs continue guard clauses

Body:
I've seen some programmers use this:

```<code>foreach (var item in items)
{
    if (item.Field != null)
        continue;

    if (item.State != ItemStates.Deleted)
        continue;

    // code
}
</code>```

instead of where I'd normally use:

```<code>foreach (var item in items.Where(i => i.Field != null && i.State != ItemStates.Deleted))
{
    // code
}
</code>```

I've even seen a combination of both. I really like the readability with 'continue', especially with more complex conditions. Is there even a difference in performance? With a database query I'm assuming there would be. What about regular lists?

Body:
I would regard this as an appropriate place to use command/query separation. For example:

// query
var validItems = items.Where(i => i.Field != null && i.State != ItemStates.Deleted);
// command
foreach (var item in validItems) {
    // do stuff
}

This also allows you to give a good self-documenting name to the query result. It also helps you see opportunities for refactoring, because it's much easier to refactor code that only queries data or only mutates data than mixed code that tries to do both.

When debugging, you can break before foreach to quickly check whether the contents of validItems resolve to what you expect. You don't have to step into the lambda unless you need to. If you do need to step into the lambda, then I suggest factoring it out into a separate function, then step through that instead.

Is there a difference in performance? If the query is backed by a database, then the LINQ version has the potential to run faster, because the SQL query may be more efficient. If it's LINQ to Objects, then you won't see any real performance difference. As always, profile your code and fix the bottlenecks that are actually reported, rather than trying to predict optimisations in advance.


答: When I'm at the office and I need to maintain my focus, I close my e-mail client.  Nothing destroys efficiency for me faster than the constant temptation to "take a quick look" at whatever message just arrived.  I've also been toying with the Pomodoro Technique for managing disruptions and maintaining focus.</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: Tim Trout


答:
Exposing the properties as public and having separate classes do the XML representation is a pretty standard pattern. There are lots of XML/JSON etc libraries out there for converting class objects to various data representations, and your code is going to be most useful if you leave it compatible with all of those.

And for what it's worth, I don't really see the difference in terms of third party dependencies. If it is going to be part of the XML representation, then it is part of the public interface and should be public.

Title: Class design dilemma: Encapsulation vs Single Responsibility/Separation of Concerns

Body:
I'm working on a class that represents an object with multiple representations - one is an XML type representation used by an automatic ordering system, the other is a POJO-based representation used by a monitoring tool.

The problem I'm running into is that I seem to have to make trade-off between encapsulating the object's internal data and designing my application according to the principle of "separation of concerns" or "single responsibily per class".

Let's look at the class in more detail:

```<code>public class MyObject {
    private Object field1;
    private Object field2;
    private Object field3;
    ...
    private Object field100;
}
</code>```

(Yes it's quite a big ugly monster, something I have no control over).

If I follow the principle of separation of concerns (the way I understand it anyway), I will have to add getters for every field in this class and have a separate XMLBuilder class for the XML representation, and a PojoBuilder for the Monitoring tool representation:

```<code>public class XMLBuilder {

    public XML asXml(MyObject obj) {
        return "<tag1>" + object.getField1() + "</tag1>"
               "<tag2>" + object.getField2() + "</tag2>"
               ...
               ;
        }
}
</code>```

This seems to me to break the principle of encapsulation - I have to expose a lot of the internal data on my class just to provide a representation for it. If I pass my object to other systems, I have no control whether these sub-systems may become dependent on arbitrary fields (i.e. field45), which means that future changes to the structure of this object may become difficult as there are now other possible dependencies on it.

An alternative approach, advocated by Allen Holub (http://www.javaworld.com/article/2073723/core-java/why-getter-and-setter-methods-are-evil.html) for example, is to do the representation inside the class:

```<code>public class MyObject {

    ...

    public XML asXml() {
        return "<tag1>" + field1 + "</tag1>"
               "<tag2>" + field2 + "</tag2>"
               ...
               ;
    }

    public Object asMonitor() {
        ...
    }

 }
</code>```

To me, this solution seems great, as the class never exposes any private fields. The representation generators have access to all the information it needs, and the object itself can be safely passed to other sub-systems without the worry that another module would depend on internals.

Now, when I implement this, my colleagues all raise the issue of "Separation of concerns". The problem, they say, is that the MyObject class now have knowledge of things like XML representations and POJO represantions, which means that if the XML representation changes, you now have to make modifications inside the actual class itself, instead of just updating an "XML ruleset" or some other external configuration.

Holub's solution is to use a Builder pattern:

```<code>public class MyObject {

...

    public void buildContent(MyObjectBuilder builder) {
        builder.setField1(field1);
        builder.setField2(field2);
    }
 }

 public class XMLBuilder implements MyObjectBuilder {

     ...

     public void setField1(Object field1) {
         content += "<tag1>" + field1 + "</tag1>";
     }

     public XML asXML() {
         return content;
     }

     ...
 }
</code>```

but this seems hardly better than the first approach - instead of exposing data as getters, it is now implicitly exposed via a builder. OK, I understand that with the builder I may have additional control over how my object represents itself, but is that iota of control worth the increased complexity in the code base? Changes to the structure of MyObject will still likely result in downstream dependencies requiring updates, so I'm not entirely sure if much have been gained here (except that there are technically no getters).

Is this a case where you simply have to choose your poison? Or is there a magical middle ground that reduces all these issues? What are the common strategies for dealing with this?


答:
This seems to me to break the principle of encapsulation - I have to expose a lot of the internal data on my class just to provide a representation for it.

Not really. In one approach, you expose data and structure through 100 getters, in the other, you expose essentially the same data and structure through an XML with 100 tags. From the viewpoint of dependencies and encapsulation, there is no (!)  difference between these two solutions.

Moreover, you should consider not to implement this "manually". There are some reflection based libraries (like XStream) which can do an Xml serialization / deserialization for you (some more are mentioned in this former SO post). They work fine with private attributes, so no need to write any additional getters and setters. Using such a library will allow you to stick to the SRP - your object will not know anything about the serialization format.

If you really cannot use one of those "out of the box" XML serializers, you may consider to implement this based on reflection by yourself. That will surely safe you from writing the same kind of boilerplate code again and again.

If you do not want to use reflection and go the route of writing similar code for each individual attribute, consider to provide a method asMap in your class MyObject which delivers you a more or less "format neutral" representation of your object like a Map<String,String> (with the field names or tag names as keys). Your XmlBuilder then can take this as input and reformat the map into the final xml format.


问:
Read data from a device through usb port at high frequency
I need to know if I can get acceleration data from an IMU at 500Hz via USB.

I've been going through the code that the manufacturer provides and trying to improve it. Right now I cannot go faster than 166Hz. Things I've tried:

Switched from streaming mode to polling. The reason is that in streaming mode the SDK of the manufacturer uses the ioctl library to know if there is new data to be read. The faster I would go was 10Hz. In polling mode, every N milliseconds data gets read from the port using a standard read command. I went from 10Hz to 166Hz, that is, for N=6. But with N<6 I get no improvement. 166Hz is a ceiling right now.

Increased the process priority. This has no effect at all. Maybe because I'm only running the browser and the code I'm working on?

Yes, I know linux is not a real time system. At the end of the day I'll have to live with that. I may use xenomai later on the code. But right now I need to know how fast I can go. Not theoretically, but in a real application. Any ideas about how to increase the performance?

EDIT: This are the timestamps of the time I get the data, in millisencods. Note the bursts.

```<code> 1449258970519
 1449258970519
 1449258970525
 1449258970531
 1449258970531
 1449258970543
 1449258970543
 1449258970543
 1449258970549
 1449258970555
 1449258970555
 1449258970562
 1449258970567
 1449258970567
 1449258970573
 1449258970579
 1449258970579
 1449258970585
</code>```

EDIT: The amount of data that I have to transfer is very small... say at most 16 floats, plus some headers. I can safely assume 128 bytes is enough. So 128x1000 is still A LOT less than the 480 Mpbs that USB 2 offers.

答:
After looking around quite a log, reading manuals, and getting some output from the linux kernel USB mailing list, I'm going to say that is not a good idea to use a USB for 500Hz continous data transfer.

At first I thought that it should be possible, and the math proved it. Meaning, if USB 2.0 offers 480Mbs, I should be able to poll my imu for a few floats at 500Hz. I think that I needed at most 128kps. Well, as proposed by someone at the linux kernel mailing list (someone who very kindly answered all my questions!) I profiled the data transfer and it came at 27 Kbs, which is way lower than the theoretical 480 Mpbs of USB 2.0.

Then, on several places I found reference to the issues of "bursts" in USB data. For reasons that I don't fully understand yet, that's how the USB driver works.

So, for frequencies above 150 (maybe even lower), USB is not your guy if you need to get data at regular intervals.

I tested different drivers, on different computers, and always got a similar result. Data in burst after a 6ms sampling interval.


问:
Why does XmlWriter.Create have output parameters?
Why does XmlWriter's create methods have output parameters?

For example (from MSDN)

```public static XmlWriter Create(
    StringBuilder output,
    XmlWriterSettings settings
)

output
  Type: System.Text.StringBuilder
  The StringBuilder to which to write to.
  Content written by the XmlWriter is appended to the StringBuilder.```

Why doesn't create not take the StringBuilder and instead of Flush have toString or toStream or toStringBuilder if thats whats really wanted.

I'm not asking how to use XmlWriter, I'm trying to understand the reasoning why it was constructed this way. I assume there is a reason, or even it to be a known pattern with advantages and disadvantages, I'd like to know more about this

答:
That's not an "output" parameter (even though it's called "output"); it's just a reference to a StringBuilder.

Why doesn't create not take the StringBuilder and instead of Flush have toString or toStream or toStringBuilder if thats whats really wanted.

Because it uses the StringBuilder during the writing process.


问:
Function Overloading in Python
My book says that function overloading is not possible in python but it asks me questions like:

WAP to find out the volume of a cube,cuboid and cylinder using function overloading.

Do I have to involve decorators here?

How am I supposed to involve functional overloading in my program?

I saw a similar question where wraps from functools was used but failed to understand it.

If functional overloading is not involved then it is child's play...

P.S-I am in grade 12 and we haven't been taught much about decorators.

答:
If you're using Python 3.4 or newer, you have access to functools.singledispatch (thanks to PEP 443), which lets you overload functions (preferably unary) much like you would in a language like Java.

If you define your various polyhedra as classes, you can dispatch on their types, like so:

```<code>import math
from functools import singledispatch

class Cube:
    def __init__(self, x):
        self.x = x

class Cuboid:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

class Cylinder:
    def __init__(self, *, r, h):
        self.r = r
        self.h = h

# Mark this function as single-dispatchable.
@singledispatch
def volume(polyhedron):
    pass # Or throw an exception, or something like that.

def _volume_cube(cube):
    return cube.x ** 3

def _volume_cuboid(cuboid):
    return cuboid.x * cuboid.y * cuboid.z

def _volume_cylinder(cylinder):
    return math.pi * (cylinder.r) ** 2 * cylinder.h

# Register handlers for the types for which you can compute volumes.
volume.register(Cube, _volume_cube)
volume.register(Cuboid, _volume_cuboid)
volume.register(Cylinder, _volume_cylinder)
</code>```

Now, you can do this:

```<code>>>> cube = Cube(4)
>>> volume(cube)
64
>>> cuboid = Cuboid(3, 5, 7)
>>> volume(cuboid)
105
>>> cylinder = Cylinder(r=2, h=4)
>>> volume(cylinder)
50.26548245743669
</code>```

If you're using a version older than 3.4, you don't really have any good options for this sort of transparent single dispatch (though you could always just backport functools.singledispatch if you're on an earlier 3.x - it's written in pure Python and I don't think it relies on any new 3.4 features). You could, instead, have a function volume(cube=None, cuboid=None, cylinder=None), or volume(polyhedron) and dispatch on type(polyhedron) inside the function, or do some magic with **kwargs.

All that said, I somehow doubt that your book wants you to use functools.singledispatch - I'd hazard a guess that somebody just copied the problems out of a C++ or Java book without really thinking about it.

Title: Function Overloading in Python

Body:
If you're using Python 3.4 or newer, you have access to functools.singledispatch (thanks to PEP 443), which lets you overload functions (preferably unary) much like you would in a language like Java.

If you define your various polyhedra as classes, you can dispatch on their types, like so:

import math
from functools import singledispatch

class Cube:
    def __init__(self, x):
        self.x = x

class Cuboid:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

class Cylinder:
    def __init__(self, *, r, h):
        self.r = r
        self.h = h

# Mark this function as single-dispatchable.
@singledispatch
def volume(polyhedron):
    pass # Or throw an exception, or something like that.

def _volume_cube(cube):
    return cube.x ** 3

def _volume_cuboid(cuboid):
    return cuboid.x * cuboid.y * cuboid.z

def _volume_cylinder(cylinder):
    return math.pi * (cylinder.r) ** 2 * cylinder.h

# Register handlers for the types for which you can compute volumes.
volume.register(Cube, _volume_cube)
volume.register(Cuboid, _volume_cuboid)
volume.register(Cylinder, _volume_cylinder)

Now, you can do this:

>>> cube = Cube(4)
>>> volume(cube)
64
>>> cuboid = Cuboid(3, 5, 7)
>>> volume(cuboid)
105
>>> cylinder = Cylinder(r=2, h=4)
>>> volume(cylinder)
50.26548245743669

If you're using a version older than 3.4, you don't really have any good options for this sort of transparent single dispatch (though you could always just backport functools.singledispatch if you're on an earlier 3.x - it's written in pure Python and I don't think it relies on any new 3.4 features). You could, instead, have a function volume(cube=None, cuboid=None, cylinder=None), or volume(polyhedron) and dispatch on type(polyhedron) inside the function, or do some magic with **kwargs.

All that said, I somehow doubt that your book wants you to use functools.singledispatch - I'd hazard a guess that somebody just copied the problems out of a C++ or Java book without really thinking about it.


答:
It's possible the book is using incorrect wording and is actually asking you to use OO inheritance.</p>

```<code>class Shape(object):
    def volume():
        raise NotImplementedError()

class Cube(Shape):
    def __init__(self, side_length):
        self.side = side_length
    def volume():
        return self.side * self.side * self.side

class Cylinder(Shape):
    def volume():
        ...
</code>```

Title: Function Overloading in Python

Body:
My book says that function overloading is not possible in python but it asks me questions like:

WAP to find out the volume of a cube,cuboid and cylinder using function overloading.

Do I have to involve decorators here?

How am I supposed to involve functional overloading in my program?

I saw a similar question where wraps from functools was used but failed to understand it.

If functional overloading is not involved then it is child's play...

P.S-I am in grade 12 and we haven't been taught much about decorators.

Body:
It's possible the book is using incorrect wording and is actually asking you to use OO inheritance.

class Shape(object):
    def volume():
        raise NotImplementedError()

class Cube(Shape):
    def __init__(self, side_length):
        self.side = side_length
    def volume():
        return self.side * self.side * self.side

class Cylinder(Shape):
    def volume():
        ...


答:
These are all good suggestions. I would add my own productivity technique which is to know how to get things done not only with minimal code but with minimal redundancy code.

Generally this means the less data structure the better.

To make code with minimal redundancy requires creativity and willingness to do things in ways that might impose a learning curve. That's the price of the productivity. Here's one example.

Title: How to become a "faster" programmer?

OwnerDisplayName: Mike Dunlavey


问:
Why do we need both Priority and Severity?
I understand what they determine but is it really useful to assign those to issues found? I mean, it is either required to fixed quickly or not.

I know how to set them, categorize them etc. I know IEEE/ISO do require to do that. I just do not see why.

答:
In addition to other answers, consider this scenario: bug A will take 30min to fix and has 'low' severity; bug B may take 2+ weeks to fix and have 'high' severity. In addition, bug B may take a lot of discussion and coordination in dev team and perhaps outside of team; bug A may be fixed by single dev immediately. It's perfectly fine to set higher priority on bug A.

Of course 'severity' and 'priority' may be interpreted in different ways.

In a small bug tracker I made for my own use I instead preferred 'difficulty' and 'priority' where high severity issues would always have highest priority, and I might decide to delay working on them based on difficulty.

One thing I don't like about 'severity' is that it only applies to bugs and not features. It may be better to have a single list of all issues ordered by priority and difficulty as it's more directly helpful to decide 'what do I work on next?'.


问:
Should collaborators on a private Github repository each fork the repo?
I'm working on a project at the moment, and we have the source code up in a private repository on Github, with each of us as a collaborator.

What we are unclear on is how to separate each of our work.

What I think we need to do is:

Each of us needs to fork the repository

When we are ready to push our code, we then submit a pull request to the project leader's repo, who can at the same time use this as an opportunity to do a code review

When it comes to private repositories, is this what forking is supposed to be used for, or am I overcomplicating the situation?

答: This would work, or you could use a branching method where each contrib has their own branch(es), that when the team agrees, are merged with master.</p>


答:
Cloning the repo to the developer's local machine is already a kind of forking. If each developer forks the repo on GitHub, this only serves to publish their current state of work.

This can be appropriate when there is a central master repo, and many contributors that are not trusted with direct access to that repo. This works great for open-source projects where everyone can contribute and issue a pull request that is then reviewed and merged by a group of core maintainers. Using multiple repos enforces a pull-request based workflow.

In a small, trusted team, this is not necessary. To prevent different people getting in each others way, a strategy such as the Git Flow can be followed: Each small feature is implemented on a separate feature branch. When the feature is complete, it is merged into the master branch. Most teams will couple this with a pull request or code review by convention, but are trusted enough to skip that if appropriate. Whereas separate repos would lead to a developer publishing their current state on their forked but team-visible repos, in a single common repo they would push their changes to a separate feature branch. Doing all development on master/trunk is highly discouraged in most workflows.

The difference ends up being solely about access management, and not so much about the implemented workflow. You can do pull-request based workflows with either setup. From a raw Git perspective, there's not much difference between a fork and a branch – either approach essentially shares the history of the project and allows commits to be added without affecting other branches/forks. Considering this, it would be much better to share a single repo when in a trusted, closed group.

Title: Should collaborators on a private Github repository each fork the repo?

Body:
I'm working on a project at the moment, and we have the source code up in a private repository on Github, with each of us as a collaborator.

What we are unclear on is how to separate each of our work.

What I think we need to do is:

Each of us needs to fork the repository

When we are ready to push our code, we then submit a pull request to the project leader's repo, who can at the same time use this as an opportunity to do a code review

When it comes to private repositories, is this what forking is supposed to be used for, or am I overcomplicating the situation?


问:
Checking if a method returns false: assign result to temporary variable, or put method invocation directly in conditional?
Is it a good practice to call a method that returns true or false values in an if statement?

Something like this:

private void VerifyAccount()
{
    if (!ValidateCredentials(txtUser.Text, txtPassword.Text))
    {
        MessageBox.Show("Invalid user name or password");
    }
}

private bool ValidateCredentials(string userName, string password)
{
    string existingPassword = GetUserPassword(userName);
    if (existingPassword == null)
        return false;

    var hasher = new Hasher { SaltSize = 16 };
    bool passwordsMatch = hasher.CompareStringToHash(password, existingPassword);

    return passwordsMatch;
}
```

<p>or is it better to store them in a variable then compare them using if else values like this</p>

<pre class="lang-.NET prettyprint-override"><code>bool validate = ValidateCredentials(txtUser.Text, txtPassword.Text);
if(validate == false){
    //Do something
}
</code>```

I am not only referring to .NET, I am referring to the question in all programming languages it just so happens that I used .NET as an example

答:
There's another concern that has not yet been pointed out: short-circuit evaluation.  What's the difference between these two code fragments?

Ex #1:

```<code>if(foo() && bar() && baz())
{
    quz();
}
</code>```

Ex #2:

```<code>bool isFoo = foo();
bool isBar = bar();
bool isBaz = baz();
if(isFoo && isBar && isBaz)
{
    quz();
}
</code>```

These two fragments of code appear to do the same thing, but if your language supports short circuit evaluation, these two fragments are different.  Short-circuit evaluation means that the code will evaluate the minimum it needs to pass or fail a condition.  If example #1, if foo() returns false, bar() and baz() are not even evaluated.  This is useful if baz() is a long-running function call because you can skip it if either foo() returns false or foo() returns true and bar() returns false.

This is not the case in example #2.  foo(), bar(), and baz() are always evaluated.  If you are expecting bar() and baz() to exhibit side effects, you'll have problems with Example #1.  Example #1 above is actually equivalent to this:

Ex #3:

```<code>if(foo())
{
    if(bar())
    {
        if(baz())
        {
            quz();
        }
    }
}
</code>```

Be aware of these differences in your code when choosing between examples #1 and #2.

Body:
There's another concern that has not yet been pointed out: short-circuit evaluation.  What's the difference between these two code fragments?

Ex #1:

if(foo() && bar() && baz())
{
    quz();
}

Ex #2:

bool isFoo = foo();
bool isBar = bar();
bool isBaz = baz();
if(isFoo && isBar && isBaz)
{
    quz();
}

These two fragments of code appear to do the same thing, but if your language supports short circuit evaluation, these two fragments are different.  Short-circuit evaluation means that the code will evaluate the minimum it needs to pass or fail a condition.  If example #1, if foo() returns false, bar() and baz() are not even evaluated.  This is useful if baz() is a long-running function call because you can skip it if either foo() returns false or foo() returns true and bar() returns false.

This is not the case in example #2.  foo(), bar(), and baz() are always evaluated.  If you are expecting bar() and baz() to exhibit side effects, you'll have problems with Example #1.  Example #1 above is actually equivalent to this:

Ex #3:

if(foo())
{
    if(bar())
    {
        if(baz())
        {
            quz();
        }
    }
}

Be aware of these differences in your code when choosing between examples #1 and #2.


问:
Steps to begin versioning a web application
Until now, we have not had an application version strategy or version-ed our application. We are considering doing so with our next release. What are the minimum tasks necessary to transition to a version-ed application?  Answers in the form of bullet points, not necessarily in chronological order would be sufficient. It's okay to keep it high level. A few examples might be:

Determine version control name convention Major.Minor.Build.YY...

Revise on screen imaging or text to display current version

Prepare release notes template for communicating new releases to users

We're a .Net shop using TFS if that helps. If it's not obvious already, I'm not a developer. I'm the solution expert/BA acting often as the project manager.

答:
If your goal is to be able to track a version being used by a customer when this customer is reporting a bug, any technique would work. As soon as the revision number (from the version control) appears anywhere on the page, you can link the bug to the corresponding revision.

In .NET, you can easily auto-increment the version of the assembly. The remaining task is to:

Display the version number if the users are expected to report it to you (through a screenshot or manually),

Or simply store in the log when a given version was deployed on a given server: this will make it possible to determine the version by inspecting the HTTP logs (particularly useful when you monitor HTTP 500 errors, without waiting for the end users to report the errors to you.)

Additional note: release notes are fine for software products. For web apps, users simply don't care what version do they use. For example, do you know the current version of GMail? What about Office 365? Or maybe Facebook? Or Stack Exchange (yes, you can have a peek at the bottom of this page)? This is actually becoming true even for software products. Google Chrome is an excellent example. Adobe Creative Cloud is becoming more and more another example.


答:
Labels would be the important point to note. Figure out how you want to use the TFS built-in functionality that is similar to tagging in Subversion for being able to pull out a particular build of the code.

There are other ideas like continuous integration, code freezes and scheduling that can be useful but wouldn't be necessary for having versions in an app.

Continuous Integration - this is basically about running all the tests whenever someone commits code. Useful for finding old bugs that have resurfaced as someone's changes in one place may have side effects. TFS has some of this built into it.

Code Freeze - this is basically about preventing new features from being added to the main trunk while the release is stabilized. Think of this as preventing others from using a kitchen while one group is cooking in there.

Scheduling is part of the code freeze in terms of communicating when is the release ready to do basic QA testing, when does it have user acceptance testing and when is the release. Each stage is important but depending on your process not all of these will apply.

Title: Steps to begin versioning a web application

Body:
Until now, we have not had an application version strategy or version-ed our application. We are considering doing so with our next release. What are the minimum tasks necessary to transition to a version-ed application?  Answers in the form of bullet points, not necessarily in chronological order would be sufficient. It's okay to keep it high level. A few examples might be:

Determine version control name convention Major.Minor.Build.YY...

Revise on screen imaging or text to display current version

Prepare release notes template for communicating new releases to users

We're a .Net shop using TFS if that helps. If it's not obvious already, I'm not a developer. I'm the solution expert/BA acting often as the project manager.


答:
Date and time bugs

Bug:  Year-end processing will totally corrupt your database.  That's clearly a severe bug.

Date:  December 15.  The bug is very high priority.

Date:  February 1.  The bug is low priority.

Accidental launch of missile bug

Bug:  ICBM control software pukes when going from Feb 28 to Mar 1 in years divisible by 4.  The result is an uncommanded launch.

That's about as severe a bug as can exist.  Priority very low, though--is there any realistic chance the software will be in use when the condition is triggered?

Inadvertent 'bad' words on screen

Bug:  Messages overflowing their space on the screen result in an inadvertent profane reference to Bob appearing.  (Real world: We had people working in the "Final Ass" department.  "Ass" = "Assembly".)

Unfortunately, tomorrow you are making a presentation where getting the sale is make-or-break for the company.  You are making the presentation to someone named "Bob".  Severity:  Very low.  Priority:  Very high.

Title: Why do we need both Priority and Severity?

Body:
I understand what they determine but is it really useful to assign those to issues found? I mean, it is either required to fixed quickly or not.

I know how to set them, categorize them etc. I know IEEE/ISO do require to do that. I just do not see why.


问:
Programming as a conversation
I have often wondered if it would be possible to write a programming language that would work as a conversation. I would tell the computer that I want to store coordinates and it would ask what representation I would use. I would then ask to find the shortest path between points and it would ask if I want to use Djkstra's, brute force or use Floyd's? What research has been done towards producing a system like this?</p>

答:
Prolog comes close except for two things:

It doesn't ask you how to store data, it just stores it.

It won't suggest you what to do in an intelligent way.

But it does have the behavior to store facts and have rules to verify them or generate a result with it.

Title: Programming as a conversation


问:
Is 4-5 years the “Midlife Crisis” for a programming career?
I’ve been programming C# professionally for a bit over 4 years now. For the past 4 years I’ve worked for a few small/medium companies ranging from “web/ads agencies”, small industry specific software shops to a small startup. I've been mainly doing "business apps" that involves using high-level programming languages (garbage collected) and my overall experience was that all of the works I’ve done could have been more professional. A lot of the things were done incorrectly (in a rush) mainly due to cost factor that people always wanted something “now” and with the smallest amount of spendable money. I kept on thinking maybe if I could work for a bigger companies or a company that’s better suited for programmers, or somewhere that's got the money and time to really build something longer term and more maintainable I may have enjoyed more in my career. I’ve never had a “mentor” that guided me through my 4 years career. I am pretty much blog / google / self taught programmer other than my bachelor IT degree.

I’ve also observed another issue that most so called “senior” programmer in “my working environment” are really not that senior skill wise. They are “senior” only because they’ve been a long time programmer, but the code they write or the decisions they make are absolutely rubbish! They don't want to learn, they don't want to be better they just want to get paid and do what they've told to do which make sense and most of us are like that. Maybe that’s why they are where they are now. But I don’t want to become like them I want to be better. I’ve run into a mental state that I no longer intend to be a programmer for my future career. I started to think maybe there are better things out there to work on. The more blogs I read, the more “best practices” I’ve tried the more I feel I am drifting away from “my reality”. But I am not a great programmer otherwise I don't think I am where I am now. I think 4-5 years is a stage that can be a step forward career wise or a step out of where you are.

I just wanted to hear what other have to say about what I’ve mentioned above and whether you’ve experienced similar situation in your past programming career and how you dealt with it. Thanks.

答: In my opinion it's not midlife crisis - I'd say the honeymoon is over.</p>

OwnerDisplayName: Jeff

OwnerDisplayName: bernhardrusch


答:
Python does not support function overloading, however, it does give you the tools to implement it yourself in a fairly straightforward manner.

Using **kw in the parameter list will pass all arguments in a dictionary.  In order to simulate function overloading, you test for the existence of parameters yourself and dispatch appropriately:

```<code>def foo_x_y(x, y):
    print("x is %d y is %d" % (x,y))

def foo_h_l(h, l):
    print("h is %d l is %d" % (h,l))

def foo(**kw):
    if 'x' in kw and 'y' in kw:
        return foo_x_y(kw['x'], kw['y'])
    elif 'h' in kw and 'l' in kw:
        return foo_h_l(kw['h'], kw['l'])

    raise TypeError("foo() takes exactly 2 argument (%d given)" % len(kw))

>> foo(x=1, y=2)
x is 1 y is 2
>> foo(h=2, l=1)
h is 2 l is 1
>> foo(z=1)
File "foo.py", line 18, in <module>
   foo(z=1)
File "foo.py", line 13, in foo
   raise TypeError("foo() takes exactly 2 argument (%d given)" % len(kw))
TypeError: foo() takes exactly 2 argument (1 given)
</code>```

This takes more legwork, but is more flexible than overloading.  It makes it easier to "overload" in ways that involve a single core implementation, for example:

```<code>def arc_length(**kw):
    if 'diameter' not in kw:
        raise TypeError

    if 'radians' not in kw or 'degrees' not in kw:
        raise TypeError

    if 'radians' in kw and 'degrees' in kw:
        raise TypeError

    diameter = kw['diameter']

    if degrees in kw:
        radians = degrees_to_radians(kw['degrees'])
    else:
        radians = kw['radians']

    # calculate arc length using radians and diameter

 arc_length(diameter=10, degrees=30)
 arc_length(diameter=10, radians=1.2)
</code>```

Title: Function Overloading in Python

Body:
Python does not support function overloading, however, it does give you the tools to implement it yourself in a fairly straightforward manner.

Using **kw in the parameter list will pass all arguments in a dictionary.  In order to simulate function overloading, you test for the existence of parameters yourself and dispatch appropriately:

def foo_x_y(x, y):
    print("x is %d y is %d" % (x,y))

def foo_h_l(h, l):
    print("h is %d l is %d" % (h,l))

def foo(**kw):
    if 'x' in kw and 'y' in kw:
        return foo_x_y(kw['x'], kw['y'])
    elif 'h' in kw and 'l' in kw:
        return foo_h_l(kw['h'], kw['l'])

    raise TypeError("foo() takes exactly 2 argument (%d given)" % len(kw))

>> foo(x=1, y=2)
x is 1 y is 2
>> foo(h=2, l=1)
h is 2 l is 1
>> foo(z=1)
File "foo.py", line 18, in <module>
   foo(z=1)
File "foo.py", line 13, in foo
   raise TypeError("foo() takes exactly 2 argument (%d given)" % len(kw))
TypeError: foo() takes exactly 2 argument (1 given)

This takes more legwork, but is more flexible than overloading.  It makes it easier to "overload" in ways that involve a single core implementation, for example:

def arc_length(**kw):
    if 'diameter' not in kw:
        raise TypeError

    if 'radians' not in kw or 'degrees' not in kw:
        raise TypeError

    if 'radians' in kw and 'degrees' in kw:
        raise TypeError

    diameter = kw['diameter']

    if degrees in kw:
        radians = degrees_to_radians(kw['degrees'])
    else:
        radians = kw['radians']

    # calculate arc length using radians and diameter

 arc_length(diameter=10, degrees=30)
 arc_length(diameter=10, radians=1.2)


问:
Best practices for MVP pattern on Android
my team has had great success introducing MVP and the associated unit tests that go with the presenter.
We are wondering how granular we should make the interaction between the View and the Presenter.

For example, we have a screen that displays a loading icon and then makes a request for some data. When the call returns, we remove the loading icon and display the data.

In this scenario we could make the View really dumb and delegate to the Presenter on start up and be told to display the loading icon. Then the presenter would make the request and when that returns, tell the View to remove the loading icon and then make another view call with the data to be displayed.

Another way we could do this is to have the activity display the loading icon then call the presenter. The presenter would make the call, receive a callback when it returns and then call the view with the results. Its up to the activity to know to remove the loading icon and then display the data.

In the first instance the view is told explicitly everything it should do and the second only delegates 'business logic' to the presenter.

What do people think is the better approach?

答:
Here is an example of what the interface between the View and Presenter could be, from this article

```<code>interface MessageView {
  // View methods should be directives, as the View is just executing orders from the
  // Presenter.

  // Methods for updating the view
  void setMessageBody(String body);
  void setAuthorName(String name);
  void showTranslationButton(boolean shouldShow);

  // Navigation methods
  void goToUserProfile(User user);
}

interface MessagePresenter {
  // Presenter methods should mostly be callbacks, as the View is reporting events for the
  // Presenter to evaluate

  // Lifecycle events methods
  void onStart();

  // Input events methods
  void onAuthorClicked();
  void onThreeFingersSwipe();
}
</code>```

Here are a couple of interesting points to notice about this interface:

The methods to update the view should be simple and targeted on a single element. This is better than having a single setMessage(Message message) method that will update everything, because formatting what should be displayed should be the responsibility of the Presenter. For example, you might want to start displaying “You” instead of the user name if the current user is the author of the message, and this is part of your business logic.

Lifecycle events methods on the Presenter are simple and don’t have to map the (overly complicated) Android lifecycle ones. You don’t have to implement any of them, but you can implement as many as you want if the Presenter needs to take specific actions.

Input events methods on the Presenter are kept at a high level. If for example you’re trying to detect a complex gesture, like the 3 fingers swipe example, all the gesture detection should be done in the View.
You can see that there are MessagePresenter.onAuthorClicked() and MessageView.goToAuthorProfile() methods. The implementation of the View will probably have a click listener that calls this Presenter method that will call goToAuthorProfile(). Should you skip all this and just directly go to the author profile from the click listener? No! The decision of going to that profile when the author name is clicked is part of your business logic, and belongs in the Presenter.

Body:
Here is an example of what the interface between the View and Presenter could be, from this article

interface MessageView {
  // View methods should be directives, as the View is just executing orders from the
  // Presenter.

  // Methods for updating the view
  void setMessageBody(String body);
  void setAuthorName(String name);
  void showTranslationButton(boolean shouldShow);

  // Navigation methods
  void goToUserProfile(User user);
}

interface MessagePresenter {
  // Presenter methods should mostly be callbacks, as the View is reporting events for the
  // Presenter to evaluate

  // Lifecycle events methods
  void onStart();

  // Input events methods
  void onAuthorClicked();
  void onThreeFingersSwipe();
}

Here are a couple of interesting points to notice about this interface:

The methods to update the view should be simple and targeted on a single element. This is better than having a single setMessage(Message message) method that will update everything, because formatting what should be displayed should be the responsibility of the Presenter. For example, you might want to start displaying “You” instead of the user name if the current user is the author of the message, and this is part of your business logic.

Lifecycle events methods on the Presenter are simple and don’t have to map the (overly complicated) Android lifecycle ones. You don’t have to implement any of them, but you can implement as many as you want if the Presenter needs to take specific actions.

Input events methods on the Presenter are kept at a high level. If for example you’re trying to detect a complex gesture, like the 3 fingers swipe example, all the gesture detection should be done in the View.
You can see that there are MessagePresenter.onAuthorClicked() and MessageView.goToAuthorProfile() methods. The implementation of the View will probably have a click listener that calls this Presenter method that will call goToAuthorProfile(). Should you skip all this and just directly go to the author profile from the click listener? No! The decision of going to that profile when the author name is clicked is part of your business logic, and belongs in the Presenter.


问:
Inheritance hierarchy design approach - Javascript
For the below code, that creates inheritance hierarchy,

```<code>function Animal(){
    this.name = "Animal";

    // toString is a function in the main Object that every
    // object inherits from
    this.toString = function() {
        return "My name is : " + this.name;
    };
}

function Rodent(){
   this.name = "Rodent";
}

function Rat(){
  this.name = "Rat";
}

Rodent.prototype = new Animal();
Rat.prototype = new Rodent();

Rodent.prototype.constructor = Rodent;
Rat.prototype.constructor = Rat;

var caneRat = new Rat();

document.write(caneRat.toString() + "<br />");
</code>```

a little modification is done by completely replacing Rat.prototype with Rodent.prototype, as a second approach, shown below,

```<code>function Animal(){
    this.name = "Animal";

    // toString is a function in the main Object that every
    // object inherits from
    this.toString = function() {
        return "My name is : " + this.name;
    };
}

function Rodent(){
   this.name = "Rodent";
}

function Rat(){
  this.name = "Rat";
}

Rodent.prototype = new Animal();
Rat.prototype = Rodent.prototype;
Rodent.prototype.constructor = Rodent;

var caneRat = new Rat();

document.write(caneRat.toString() + "<br />");
</code>```

What are the advantages & disadvantages in the second approach of inheritance hierarchy design compared to first approach? Second approach is visualized as shown below..

答:
It's generally fairly awkward and error-prone to implement "classical inheritance" in JavaScript.  Instead, try working with the language and use behavior delegation:

```<code>var Animal = {
  setName: function(name) {
    this.name = name;
  },

  sayName: function() {
    return 'My name is: ' + this.name;
  }
};

var Rodent = Object.create(Animal);
var Rat = Object.create(Rodent);
var caneRat = Object.create(Rat);

caneRat.setName('Rat');

console.log(caneRat.sayName()); // 'My name is Rat'
</code>```

You'll probably find that you can eliminate a lot of your "subclasses" with this approach.

For more detail on prototypes in JavaScript, take a look at this.

Also, try to avoid overwriting native object methods (e.g. toString) unless you have a really good reason to do so.

Body:
It's generally fairly awkward and error-prone to implement "classical inheritance" in JavaScript.  Instead, try working with the language and use behavior delegation:

var Animal = {
  setName: function(name) {
    this.name = name;
  },

  sayName: function() {
    return 'My name is: ' + this.name;
  }
};

var Rodent = Object.create(Animal);
var Rat = Object.create(Rodent);
var caneRat = Object.create(Rat);

caneRat.setName('Rat');

console.log(caneRat.sayName()); // 'My name is Rat'

You'll probably find that you can eliminate a lot of your "subclasses" with this approach.

For more detail on prototypes in JavaScript, take a look at this.

Also, try to avoid overwriting native object methods (e.g. toString) unless you have a really good reason to do so.


答:
There was a post by Jeff Atwood on Coding Horror that said that this is supposed to be fun. And part of the job description of being a software developer is enjoying your work. Otherwise it will become a really boring and cumbersome profession for you.

The fact that you continuously search for ways to improve your work, and you keep getting informed of the new stuff and the best practices shows that you enjoy your work in nature. So my advice to you would be to start looking for a new job.

However I do not think that working for a big company will necessarily improve the working conditions. I think the best environments for software developers are small to mid-sized companies, where the people like what they are doing. The best thing to do would be to search and check-out any companies before you take a decision. Try and make sure that the new company is worth it.

Title: Is 4-5 years the “Midlife Crisis” for a programming career?

Body:
I’ve been programming C# professionally for a bit over 4 years now. For the past 4 years I’ve worked for a few small/medium companies ranging from “web/ads agencies”, small industry specific software shops to a small startup. I've been mainly doing "business apps" that involves using high-level programming languages (garbage collected) and my overall experience was that all of the works I’ve done could have been more professional. A lot of the things were done incorrectly (in a rush) mainly due to cost factor that people always wanted something “now” and with the smallest amount of spendable money. I kept on thinking maybe if I could work for a bigger companies or a company that’s better suited for programmers, or somewhere that's got the money and time to really build something longer term and more maintainable I may have enjoyed more in my career. I’ve never had a “mentor” that guided me through my 4 years career. I am pretty much blog / google / self taught programmer other than my bachelor IT degree.

I’ve also observed another issue that most so called “senior” programmer in “my working environment” are really not that senior skill wise. They are “senior” only because they’ve been a long time programmer, but the code they write or the decisions they make are absolutely rubbish! They don't want to learn, they don't want to be better they just want to get paid and do what they've told to do which make sense and most of us are like that. Maybe that’s why they are where they are now. But I don’t want to become like them I want to be better. I’ve run into a mental state that I no longer intend to be a programmer for my future career. I started to think maybe there are better things out there to work on. The more blogs I read, the more “best practices” I’ve tried the more I feel I am drifting away from “my reality”. But I am not a great programmer otherwise I don't think I am where I am now. I think 4-5 years is a stage that can be a step forward career wise or a step out of where you are.

I just wanted to hear what other have to say about what I’ve mentioned above and whether you’ve experienced similar situation in your past programming career and how you dealt with it. Thanks.

OwnerDisplayName: Nikos Steiakakis


问:
Roles and permissions: a good approach in defining permissions?
My application has users and administrators. The administrators split into two: super-admin and limited-admin. The super gets all permissions while the limited can be configured to inherit just the admin permissions that are specifically needed.

I am thinking to define my permissions the following way. Any user permission has an administrator permission:

User:

 - post_create

 - post_update

 - post_delete

Administrator:

 - administrator_post_create

 - administrator_post_update

 - administrator_post_delete

Is this a good approach? Should I rather assign to an Admin all the users permissions and then another one like 'administrator_post_manage_all' which bypasses the ownership check and allows an admin to make modification?

Edit

The following rules must be satisfied:

Only some users can create, update, delete posts; however, they must be the owners of the post to update, delete. Every user of the application should be able to read posts. My administrators should be able to update and delete any user's post.

答:
I've been dealing with these authorization issues in a dozen of softwares ago, and along the way I found this to be the best solution:

Permissions shall reflect the events (or requirements) of the system;

Users can be assigned to specific permissions;

Just use 2 single permissions for CRUD operations by entity - Read and Modify;

CRUD operations: I've never faced a situation that a user can, for example, delete or update an entity but can't create it, so if the user can modify an entity, it is intended that he can create it, update it and delete it.

But according to your requirements, users can read any post and administrators can update/delete posts of other users, so I'd model the permissions this way:

post_modify -> Users can create, update and delete posts;

post_modify_others -> Users can update and delete posts of other users;

The most important here is that the semantic and meaning of the permissions are totally aligned to your requirements, which makes implementation easier.

So, administrators would be assigned to post_modify and post_modify_others permissions, while users would be assigned to post_modify permission only.

User groups :
I usually store users and its permissions in an specific table, but if the number of users and permissions start to grow, it is a good idea to create another table to link users and permissions (for example, user group) in order to make management easier. So you'd have 2 groups - Administrator and Users - and you'd assign users to these groups, according to their roles in the system, and permissions would be assigned per group and not per users.


答:
Hey buddy, it was really good reading your question. I am glad you wrote so. You know what, you dont realize what understanding you have right now. The things you wrote make me understand what experience you have had, and believe me this experience is something that not all programmers can have in their life. You are a self driven person, self learning. Right now you are in a very mature state of mind, after working 4 years for small companies. If you would have been into big companies, you would have had nothing to be considered as an experience. Now you have an understanding of how this industry works, how things are done and how they should be done. What level these so called "seniors" have. I have a suggestion for you, if you are so good a self learner and have practiced self learning for over 4 years, why don't you try freelancing as a career. Believe me you would be working for yourself and enjoying much more.

As an ending note, dont regret what you did in the last 4 years. Its a wonderful experience and only a few have this in their lives :)

OwnerDisplayName: Ravinder Singh


问:
Is it OK to use (WTF) forms to validate against stuff from DB?
Form classes are intended (IMO) for submitted data against rules. For example: are passwords equal, is end date later than start date.

submitted data--->|Form|

Is it okay for Form classes to validate submitted data against data retrieved from a database as well? This seems like a responsibility issue, the Form class should responsible for validating and cleaning the submission alone, and checking against the DB belongs outside the class.

submitted data--->|Form|<---data from DB

Here is my example in WTForms in Python: it checks if the user id is an integer, then queries the DB to verify that it exists.

```<code>class ClientForm(Form):
    name = StringField(validators=[DataRequired(message="Invalid value")])
    user = IntegerField(validators=[DataRequired(message="Invalid value")])
    zone = IntegerField(validators=[AnyOf([i[0] for i in ZONES], message="Invalid value")])

    #validate user as real
    def validate_user(form, field):
        user = db.session.query(User).filter(User.id==form.user.data).first()
        if not user:
            raise ValidationError('Invalid user')
</code>```

The upside of adding this check to the form is convenience, WTForms handles all aspects of errors, even rendering them:

```<code>form = ClientForm(post_data)
if not form.validate():
    # render the form again with errors highlighted
    return render("client_registration_form.html", form=form)
else:
    return render("success.html")
</code>```

答:
By referencing your database directly, and especially by grabbing it out of a global, you are tightly coupling your presentation layer with your persistence layer. We should instead approach this problem with an eye to the SOLID principles.

Instead of reaching into a global object to get the database connection, we should inject that dependency in to the form validator. That way, we can depend on the abstraction of a database rather than the concretion of a piece of global state. The code becomes more flexible and testable since the dependency can be swapped out.

The better way to achieve this would be to create an intermediary object to decouple the form validation from the database completely. This intermediary object would have the database connection injected into it, then it would be injected into the form validator. This would allow the form validator to have a flexible dependency. It might look like:

```<code>class UserIDExists:
    def __init__(self, db):
        self["db"] = db

    def check(self, user_id):
        user = db.session.query(User).filter(User.id == user_id).first()
        return bool(user)
</code>```

Then your WTForms class would use the check method to determine if it should raise or not.

But there is an even better way. Instead of just creating an arbitrary class, we could create a class that is a custom WTForms validator. We would still inject it, but it would integrate in a much cleaner and more seamless way with the rest of the validators you already use.

Body:
By referencing your database directly, and especially by grabbing it out of a global, you are tightly coupling your presentation layer with your persistence layer. We should instead approach this problem with an eye to the SOLID principles.

Instead of reaching into a global object to get the database connection, we should inject that dependency in to the form validator. That way, we can depend on the abstraction of a database rather than the concretion of a piece of global state. The code becomes more flexible and testable since the dependency can be swapped out.

The better way to achieve this would be to create an intermediary object to decouple the form validation from the database completely. This intermediary object would have the database connection injected into it, then it would be injected into the form validator. This would allow the form validator to have a flexible dependency. It might look like:

class UserIDExists:
    def __init__(self, db):
        self["db"] = db

    def check(self, user_id):
        user = db.session.query(User).filter(User.id == user_id).first()
        return bool(user)

Then your WTForms class would use the check method to determine if it should raise or not.

But there is an even better way. Instead of just creating an arbitrary class, we could create a class that is a custom WTForms validator. We would still inject it, but it would integrate in a much cleaner and more seamless way with the rest of the validators you already use.


问:
Best way to represent multiple JSON response in a REST service?
I am working on a REST service in which I am trying to come up with a JSON response that I am supposed to return back. Below is the design I am able to come up with in which each line is a response for each request so we have total three response for three request wrapped around an array.

In this I will pass HTTP Status code as 200:

```<code>[
    { "response": "{\"hello\":1,\"world\":\"4\"}", "aging": "123456", "bandwidth": "100" , "error": "OK", "status": "SUCCESS" }
    { "response": "{\"hello\":2,\"world\":\"5\"}", "aging": "5432", "bandwidth": "134" , "error": "OK", "status": "SUCCESS" }
    { "response": "{\"hello\":3,\"world\":\"6\"}", "aging": "6789", "bandwidth": "234" , "error": "OK", "status": "SUCCESS" }
]
</code>```

In the same way, I can have below response as well if any request failed and send HTTP Status code as 202 since it's a partial response.

```<code>[
    { "response": "{\"hello\":1,\"world\":\"4\"}", "aging": "123456", "bandwidth": "100" , "error": "OK", "status": "SUCCESS" }
    { "response": null, "aging": "0", "bandwidth": "0" , "error": "Some Error", "status": "ERROR" }
    { "response": "{\"hello\":3,\"world\":\"6\"}", "aging": "6789", "bandwidth": "234" , "error": "OK", "status": "SUCCESS" }
]
</code>```

In the same way, I can have below response if all request failed.

```<code>[
    { "response": null, "aging": "0", "bandwidth": "0" , "error": "Some Other Error", "status": "ERROR" }
    { "response": null, "aging": "0", "bandwidth": "0" , "error": "Some Error", "status": "ERROR" }
    { "response": null, "aging": "0", "bandwidth": "0" , "error": "Some New Error", "status": "ERROR" }
]
</code>```

I am getting above JSON response by serializing below response object:

```<code>public class TestResponse {

    private final String response;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;
    private final String aging;
    private final String bandwidth;

    // .. constructors and getters here
}
</code>```

I am trying to understand, is this the best design for returning JSON response for multiple response cases in a REST service? Or is there any better way to return a JSON response with all the proper fields?

The only problem I have is - for successful response, my JSON string is escaped with slashes in response filed in my final JSON. Not sure whether that's a good approach in REST service.

My rest service will call a library which it is using internally and that library will return back a List and then I am serializing this List into JSON Array as shown above.

答:
Well if you embed a unique identifier for each request, then you can respond with a more structured class and still give the client a way to know which query failed.

```<code>public class TestResponse {
    private final List<QueryResponse> responses;
    private final List<QueryError> errors;
    // .. constructors and getters here
}

public class QueryResponse {
    private final int queryID;
    private final String response;
    private final String aging;
    private final String bandwidth;
}

public class QueryError {
    private final int queryID;
    private final int errorCode;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;
}
</code>```

The point with this type of smarter organization means you can deal with all the responses and errors as they are generated and not bother transmitting or parsing portion unnecessarily. e.g. just check the length or loop through all the errors and responses.

If you don't like that order of the successful and failed queries are split and want to preserve the original query order, then rearrange it so query responses can contain response data structure and response error structure. For each QueryResponse you'd just check if error or response is null.

```<code>public class QueryResponse {
    private final ResponseData response = null;
    private final ResponseError error = null;
}

public class ResponseData {
    private final String response;
    private final String aging;
    private final String bandwidth;
}

public class ResponseError {
    private final int errorCode;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;
}
</code>```

Hope this helps. You asked for an opinion/idea.

Update: With JSON you shouldn't be too hung up on the transmitted format of the data. Serialization and Deserialization should take care of that for you unless you're trying to parse the result, which you should just avoid if possible. There are JSON libraries for every programming language out there. I didn't mind using GSON.

A sample JSON message for maybe the above/last example could look like:

```<code>[
    {
        "response": {
            "response": "{\"hello\":1,\"world\":\"4\"}",
            "aging": "123456",
            "bandwidth": "100"
        },
        "error": null
    },
    {
        "response": null,
        "error": {
            "errorCode": 100,
            "error": "Some Error Enum Value",
            "status": "It's an error, but this should be a message?"
        }
    }
]
</code>```

Note that the "response" variable name should probably change so it doesn't appear twice at different nested levels. This is just something I typed up cold, so it's not perfect.

Body:
Well if you embed a unique identifier for each request, then you can respond with a more structured class and still give the client a way to know which query failed.

public class TestResponse {
    private final List<QueryResponse> responses;
    private final List<QueryError> errors;
    // .. constructors and getters here
}

public class QueryResponse {
    private final int queryID;
    private final String response;
    private final String aging;
    private final String bandwidth;
}

public class QueryError {
    private final int queryID;
    private final int errorCode;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;
}

The point with this type of smarter organization means you can deal with all the responses and errors as they are generated and not bother transmitting or parsing portion unnecessarily. e.g. just check the length or loop through all the errors and responses.

If you don't like that order of the successful and failed queries are split and want to preserve the original query order, then rearrange it so query responses can contain response data structure and response error structure. For each QueryResponse you'd just check if error or response is null.

public class QueryResponse {
    private final ResponseData response = null;
    private final ResponseError error = null;
}

public class ResponseData {
    private final String response;
    private final String aging;
    private final String bandwidth;
}

public class ResponseError {
    private final int errorCode;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;
}

Hope this helps. You asked for an opinion/idea.

Update: With JSON you shouldn't be too hung up on the transmitted format of the data. Serialization and Deserialization should take care of that for you unless you're trying to parse the result, which you should just avoid if possible. There are JSON libraries for every programming language out there. I didn't mind using GSON.

A sample JSON message for maybe the above/last example could look like:

[
    {
        "response": {
            "response": "{\"hello\":1,\"world\":\"4\"}",
            "aging": "123456",
            "bandwidth": "100"
        },
        "error": null
    },
    {
        "response": null,
        "error": {
            "errorCode": 100,
            "error": "Some Error Enum Value",
            "status": "It's an error, but this should be a message?"
        }
    }
]

Note that the "response" variable name should probably change so it doesn't appear twice at different nested levels. This is just something I typed up cold, so it's not perfect.


问:
Tips for working with badly designed software
Currently in my job im working with a lot of older php systems which don't follow normalised design patterns and are frankly, a mess.

As an ethical developer and someone who always strives to better what Im working on, but also keep within the budget of my employer and their clients, what are my obligations here?

Most of the systems should be rewritten, but often the budget only allows for bodge jobs to fix minor issues. Apart from writing tests, what can I do to both fit within the budget but also add value and integrity to the code?

答:
In my experience all you can do is inform your client on the state of their sites and be ready to help if they ask. They can make the value judgement.

If you really want to help, offer to document the project/site structure that needs the most work with a recommendation. Maybe if they see the specific scope of the situation they'll either commit to a larger project, or at least be aware of the scope.

Also, never over embellish or over estimate your position just to make a point. If the previous work really sucks, it'll speak for itself. Consider that at one point you too probably produced something of questionable longevity that someone else is bitching about now. Who knows, maybe the frameworks and languages you'd recommend today will prove to be a costly PITA for someone else.


问:
When should I use Perl's DBIx::Class?
DBIx::Class is a popular Perl interface to any database that you can connect to through DBI. There is good documentation for its technical details, but scant information about its proper use (including the situations where you probably don't want it).

In many situations, people reach for it reflexively because they think they should use it for everything that involves a database. However, I most often seen it misused to the point where it becomes a pain point. My question during code and architecture reviews is always "What benefit is Foo giving you?" Most often, the developers I see in these situations can't form a coherent answer to that. But then, they also often don't understand simple SQL.

For the past couple of months I've been asking people "Why do you use DBIx::Class?" and have only received one good answer (and that person also was able to answer the follow-up "When wouldn't you use it"). Peter Rabbitson, the lead developer, got close to an answer in his interview on FLOSS Weekly, but it's a bit buried in the middle of the interview.

So, how can I decide whether using DBIx::Class is appropriate for a project?

答:
To know when to use something, it's important to understand what the thing's purpose is. What the product's goal is.

DBIx::Class is an ORM - Object-Relational Mapper. An ORM takes the Relational/Set-based relational database data structures and maps it to an Object tree. The traditional mapping is one object per row, using the table's structure as a class description. Parent-child relationships in the database are treated as containering relationships between objects.

That's the bones of it. But, that doesn't help you decide if you should use an ORM. ORMs are primarily useful when the following are true:

You use an relational database.

Your data is largely used for OLTP (Online Transaction Processing).

You don't write reports within your application.

The largest strength an ORM has is constructing good SQL to walk a tree graph overlaid on top of the relational data structure. The SQL is often hairy and complex, but that's the price of managing the impedance mismatch.

While ORMs are very good at writing row-extraction SQL, they are very poor at writing collating SQL. This is the type of SQL that reports are built on. This sort of collation is built using different tools, not an ORM.

There are many ORMs in various languages, several in Perl. Other mappers are Class::DBI and Rose::DB. DBIx::Class is often considered better than the others largely on the strength of its resultsets. This is a concept where the SQL generation is separated from SQL execution.

Update: In response to Ovid, DBIx::Class (through SQL::Abstract) provides the ability to specify both what columns to return as well as what index hints to use.

In general, though, if you are wanting to do this, then you're better off not using an ORM for that specific query. Remember - the primary purpose of an ORM is to map rows in a table to objects of a class whose attributes are the columns of the table. If you're only populating some of the attributes, then potential users of that object won't know which attributes are populated or not. This leads to horrific defensive programming and/or a general hatred of ORMs.

Almost always, the desire to use index hints or limit which columns are returned is either an optimization for speed and/or an aggregating query.

Aggregating queries are the use case ORMs are NOT designed for. While DBIx::Class can create aggregating queries, you aren't creating an object graph, so just use DBI directly.

Performance optimizations are used because the data being queried is too large for the underlying database, regardless of how you access it. Most relational databases are ideal for tables with up to 1-3MM rows running off of SSDs where most of the data+indices fits in RAM. If your situation is bigger than this, then every relational database will have issues.

Yes, a great DBA can make tables with 100MM+ rows function in Oracle or SQL*Server. If you're reading this, you don't have a great DBA on staff.

All of this said, a good ORM does more than just create object graphs - it also provides an introspectible definition of your database. You can use this to help create ad-hoc queries and consume them as you would with DBI, without creating the object graph.

Title: When should I use Perl's DBIx::Class?