问:
ASP.Net or WPF(C#)?
Our team is divided on this and I wanted to get some third-party opinions.

We are building an application and cannot decide if we want to use .Net WPF Desktop Application with a WCF server, or ASP.Net web app using jQuery. I thought I'd ask the question here, with some specs, and see what the pros/cons of using either side would be. I have my own favorite and feel I am biased.

Ideally we want to build the initial release of the software as fast as we can, then slow down and take time to build in the additional features/components we want later on. Above all we want the software to be fast. Users go through records all day long and delays in loading records or refreshing screens kills their productivity.

Application Details:

I'm estimating around 100 different screens for initial version, with plans for a lot of additional screens being added on later after the initial release.

We are looking to use two-way communication for reminder and event systems

Currently has to support around 100 users, although we've been told to allow for growth up to 500 users

We have multiple locations

Items to consider (maybe not initially in some cases but in future releases):

Room for additional components to be added after initial release (there are a lot of of these... perhaps work here than the initial application)

Keyboard navigation

Performance is a must

Production Speed to initial version

Low maintenance overhead

Future support

Softphone/Scanner integration

Our Developers:

We have 1 programmer who has been learning WPF the past few months and was the one who suggested we use WPF for this.

We have a 2nd programmer who is familiar with ASP.Net and who may help with the project in the future, although he will not be working on it much up until the initial release since his time is spent maintaining our current software.

There is me, who has worked with both and am comfortable in either

We have an outside company doing the project management, and they are an ASP.Net company.

We plan on hiring 1-2 others, however we need to know what direction we are going in first

Environment:

General users are on Windows 2003 server with Terminal Services. They connect using WYSE thin-clients over an RDP connection. Admin staff has their own PCs with XP or higher. Users are allowed to specify their own resolution although they are limited to using IE as the web browser.

Other locations connects to our network over a MPLS connection

Based on that, what would you choose and why?

答:
do you need a higly responsive application for people to use all day long? use WPF
; you'll find it easier to reuse GUI components in WPF over ASP/MVC also (IMHO)

yes, jquery et al are great, silverlight is cool, but desktop apps are still more efficient

for the back-end, WCF is fine

Title: ASP.Net or WPF(C#)?


问:
Initializing a variable as undefined
Doing some refactoring, I noticed an unusual pattern I'm not familiar with. Properties and variables that do not yet have a value are initiated with undefined declared explicitly, despite the fact that value-less variables and object properties would evaluate to undefined anyways:

```<code>var foo = undefined;
this.prop = undefined;
</code>```

Is there a reason to do this?

答: It's possible the author came from an environment where all variables were required to be initialized when declared. Some code-checking tools will also complain if variables are not initialized before they are used (even if the first use is to assign a value).</p>

ContentLicense: CC BY-SA 3.0

Title: Initializing a variable as undefined


问:
How to safeguard a REST API for only trusted mobile applications
How do I make sure my REST API only responds to requests generated by trusted clients, in my case my own mobile applications? I want to prevent unwanted requests coming from other sources. I don't want users to fill in a serial key or whatever, it should happen behind the scenes, upon installation, and without any user interaction required.

As far as I know, HTTPS is only to validate the server you are communicating with is who it says it is. I'm ofcourse going to be using HTTPS to encrypt the data.

Is there a way to accomplish this?

Update:
The user can perform read-only actions, which do not require the user to be logged in, but they can also perform write actions, which do require the user to be logged in (Authentication by Access Token). In both cases I want the API to respond to requests coming only from trusted mobile applications.

The API will also be used for registering a new account through the mobile application.

Update 2: It seems like there are multiple answers to this, but I honestly don't know which one to flag as the answer. Some say it can be done, some say it can't.

答:
As far as I know, HTTPS is only to validate the server you are communicating with is who it says it is.

In fact, you can use SSL to authenticate both the client and the server.  Or, stated differently, "yes, you can use client certificates".

You'll need to...

look at the SSL library you're using to determine how to specify client certificates in the mobile device,

write code or configure your HTTPS server so that it only accepts connections from trusted, registered clients.

come up with a mechanism to add trusted client certificates into your server

come up with a mechanism to remove no-longer-trusted client certificates from your server

You can have the mobile application store the certificate wherever you want.  Since you want it application-specific authentication, you should consider storing the certificate in a protected disk location (on Android, you could create a "config" table in your SQLite database, and a row for your certificate and another for your private key).


问:
Static factory vs factory as a singleton
In some of my code, I have a static factory similar to this:

```<code>public class SomeFactory {

    // Static class
    private SomeFactory() {...}

    public static Foo createFoo() {...}

    public static Foo createFooerFoo() {...}
}
</code>```

During a code review, it was proposed that this should be a singleton and injected.  So, it should look like this:

```<code>public class SomeFactory {

    public SomeFactory() {}

    public Foo createFoo() {...}

    public Foo createFooerFoo() {...}
}
</code>```

A few things to highlight:

Both factories are stateless.

The only difference between the methods are their scopes (instance vs static).  The implementations are the same.

Foo is a bean that does not have an interface.

The arguments I had for going static was:

The class is stateless, therefore doesn't need to be instantiated

It seems more natural to be able to call a static method than to have to instantiate a factory

The arguments for the factory as a singleton was:

Its good to inject everything

Despite the statelessness of the factory, testing is easier with injection (easy to mock)

It should be mocked when testing the consumer

I have some serious issues with the singleton approach since it seems to suggest that no methods should ever be static.  It also seems to suggest that utilities such as StringUtils should be wrapped and injected, which seems silly.  Lastly, it implies that I'll need to mock the factory at some point, which doesn't seem right.  I can't think of when I'd need to mock the factory.

What does the community think?  While I don't like the singleton approach, I don't seem to have a terribly strong argument against it.

答:
Why would you separate your factory from the object-type it creates?

```<code>public class Foo {

    // Private constructor
    private Foo(...) {...}

    public static Foo of(...) { return new Foo(...); }
}
</code>```

This is what Joshua Bloch describes as his Item 1 on page 5 of his book, "Effective Java."  Java is verbose enough without adding extra classes and singletons and whatnot.  There are some instances where a separate factory class makes sense, but they are few and far between.

To paraphrase Joshua Bloch's Item 1, unlike constructors, static factory methods can:

Have names that can describe specific kinds of object creation (Bloch uses probablePrime(int, int, Random) as an example)

Return an existing object (think: flyweight)

Return a sub-type of the original class or an interface it implements

Reduce verbosity (of specifying type parameters - see Bloch for example)

Disadvantages:

Classes without a public or protected constructor cannot be subclassed (but you can use protected constructors and/or Item 16: favor composition over inheritence)

Static factory methods do not stand out from other static methods (use a standard name like of() or valueOf())

Really, you should take Bloch's book to your code reviewer and see if the two of you can agree to Bloch's style.

Body:
Why would you separate your factory from the object-type it creates?

public class Foo {

    // Private constructor
    private Foo(...) {...}

    public static Foo of(...) { return new Foo(...); }
}

This is what Joshua Bloch describes as his Item 1 on page 5 of his book, "Effective Java."  Java is verbose enough without adding extra classes and singletons and whatnot.  There are some instances where a separate factory class makes sense, but they are few and far between.

To paraphrase Joshua Bloch's Item 1, unlike constructors, static factory methods can:

Have names that can describe specific kinds of object creation (Bloch uses probablePrime(int, int, Random) as an example)

Return an existing object (think: flyweight)

Return a sub-type of the original class or an interface it implements

Reduce verbosity (of specifying type parameters - see Bloch for example)

Disadvantages:

Classes without a public or protected constructor cannot be subclassed (but you can use protected constructors and/or Item 16: favor composition over inheritence)

Static factory methods do not stand out from other static methods (use a standard name like of() or valueOf())

Really, you should take Bloch's book to your code reviewer and see if the two of you can agree to Bloch's style.


问:
How Stack and Heap is allocated for threads under the same process in Windows?
Stack for different thread is different.but what about Heap. If Heap is different for different threads, then how they share objects?</p>

答:
AFAICR, for a new user-space thread, the stack space is allocated in virtual memory by the operating system using the kernel-side of ZwAllocateVirtualMemory() routine. The stack pointer for the thread is set to the top of this block and the thread procedure is started (among some other setup, omitted here).

When the thread needs to dynamically allocate on the heap, it could use 'new', 'malloc()' or GlobalAlloc() - they all eventually go through the Native API 'RtlAllocateHeap()' which will allocate from a process heap. As there will be multiple threads doing this, it has to be thread-safe (by default, there is an option opt-out flag).

Once memory is allocated on the heap, any thread is free to do whatever it wants with it - there are not locks enforced by the operating system. It is up to the language/runtime to serialise access to the object if that is desired. Some languages have this built-in (e.g. 'synchronised'), for others it is all manual.


问:
REST API at backend and MVC Javascript framework at client side
I am building an online social network. I have finished writing RESTful API service using Django. This will return only JSON response (No HTML will be generated from server side) so that this JSON response can be used to build native smartphone apps. API service being common to all clients.

My question is, since there is no HTML response from server side, can the MV* Javascript Frameworks like Angular / Backbone / Ember take care of complete Front-end, right from generating HTML page with CSS?

答:
Yes to any of the MV* frameworks.  All of them were designed to work with a REST API.  Those frameworks will take the JSON data returned from the REST service, store it in memory on the client, and also use that data to generate the HTML.

A good sample app for using a Rest API with Backbone/Angular a couple of friends and I put together can be found up on Github.  It doesn't do a whole lot, but it should be a good place to start. The App is written in ASP.NET MVC, but all the UI (specifically the angular section) is straight HTML/CSS.  You can easily pull that piece out into a seperate project and everything would still work.

https://github.com/itsjason/OrderTracker


问:
Multiple APIs, or one API with a "chooser" parameter?
Say you have a web service, which adds business logic on top of a data source. What each API of this service pretty much looks like is - given a set of constraints, give me the items from the data source that satisfy these constraints. You can say you get a "view" of the data source back from the API.

Now, over time you get asked to return different kinds of views over the data source. You have the option to either add new APIs for each "sufficiently distinct" view, or to switch gears and provide a getFooDataView() API, which takes a parameter that specifies what kind of view you want. You have several competing pressures for deciding which way to go:

The existing big client of your service would prefer to be lazy, and not have to code up to new APIs when new views over the data are needed.

But, some of your request parameters (constraints) only make sense for some views, and not for others - you'd have to make your API contract looser by saying "well if you want XYZ view, setting the "foo" parameter will have no effect", with the unfortunate side effect that you can't make "foo" a required parameter even if it is so for some of the views.

It's becoming more and more the case that new clients want to leverage your service. You can't decide which would be more confusing to them - having to pick between different, but tighter-defined APIs, and one API where they have to know what combination of parameters really gives them what they want.

To distill this, when do you draw the line that something should be its own API as opposed to a variation of an existing API? Different people you have to work with have different views about what makes two client requests semantically distinct, so it can be hard to drive consensus about this matter. You also want to make sure that your service isn't prohibitively difficult for future clients to consume. What are some best practices arount making this kind of choice?

答:
Personally I would lean towards smaller, tighter APIs. I don't think that it follows that having one one-size-fits-all API makes something simpler to use - in fact perhaps the converse since you need to figure out the right combination of loosely-typed "ju-ju" to get what you want whereas a tighter API can be made more self-explanatory. You are just hiding the complexity instead of making it explicit.

It's also likely that your one API will become ever more complex as it wraps more and more functionality, whereas the tighter APIs remain focussed and lean.

This smacks of the Interface Segregation Principle on a grander scale.

There are always other ways (such as good guidance) to help clients choose the right approach.


答:
I'm sure you're comfortable with dealing with user logins, and with communications over SSL, so I'm going to focus on what I think it the more interesting part of the question: how to ensure that your read-only actions - which do not require the user to be authenticated - are only accepted from your own client apps?

Before anything else, there is the downside that fNek hinted at in an earlier answer - your client apps are in the hands of potentially hostile users. They can be examined, their communications inspected, their code disassembled. Nothing I am going to suggest will allow you to guarantee that someone doesn't reverse-engineer your client and abuse your REST API. But it should put a barrier in front of any casual attempts.

Anyway, a common approach is:

The client contains a secret

When making a request, it concatenates the request parameters with the secrets, and hashes the result

This hash is sent with the request, and checked by the server

e.g., imagine a GET request for /products/widgets

Let's say the client secret is "OH_HAI_I_IZ_SECRET"

Concatenate the HTTP verb, and the URL, and the secret:

```<code>GET/products/widgetsOH_HAI_I_IZ_SECRET
</code>```

And take an SHA-1 hash of that:

```<code>4156023ce06aff06777bef3ecaf6d7fdb6ca4e02
</code>```

Then send that along, so the request would be for:

```<code>GET /products/widgets?hash=4156023ce06aff06777bef3ecaf6d7fdb6ca4e02
</code>```

Finally, to prevent someone from at least replaying individual requests, take a timestamp also, and add that to the parameters and the hash. e.g. right now, in Unix time, is 1384987891. Add that to the concatenation:

```<code>GET/products/widgetsOH_HAI_I_IZ_SECRET1384987891
</code>```

Hash that:

```<code>2774561d4e9eb37994d6d71e4f396b85af6cacd1
</code>```

And send:

```<code>GET /products/widgets?time=1384987891&hash=2774561d4e9eb37994d6d71e4f396b85af6cacd1
</code>```

The server will check the hash and also verify that the timestamp is current (e.g. within 5 minutes to allow for clocks not being perfectly in sync)

Warning! Since you're talking about mobile apps, there's a definite risk that someone's phone will have it's clock wrong. Or timezone wrong. Or something. Adding the time to the hash will probably break some legit users, so use that idea with caution.

Title: How to safeguard a REST API for only trusted mobile applications

Body:
How do I make sure my REST API only responds to requests generated by trusted clients, in my case my own mobile applications? I want to prevent unwanted requests coming from other sources. I don't want users to fill in a serial key or whatever, it should happen behind the scenes, upon installation, and without any user interaction required.

As far as I know, HTTPS is only to validate the server you are communicating with is who it says it is. I'm ofcourse going to be using HTTPS to encrypt the data.

Is there a way to accomplish this?

Update:
The user can perform read-only actions, which do not require the user to be logged in, but they can also perform write actions, which do require the user to be logged in (Authentication by Access Token). In both cases I want the API to respond to requests coming only from trusted mobile applications.

The API will also be used for registering a new account through the mobile application.

Update 2: It seems like there are multiple answers to this, but I honestly don't know which one to flag as the answer. Some say it can be done, some say it can't.

Body:
I'm sure you're comfortable with dealing with user logins, and with communications over SSL, so I'm going to focus on what I think it the more interesting part of the question: how to ensure that your read-only actions - which do not require the user to be authenticated - are only accepted from your own client apps?

Before anything else, there is the downside that fNek hinted at in an earlier answer - your client apps are in the hands of potentially hostile users. They can be examined, their communications inspected, their code disassembled. Nothing I am going to suggest will allow you to guarantee that someone doesn't reverse-engineer your client and abuse your REST API. But it should put a barrier in front of any casual attempts.

Anyway, a common approach is:

The client contains a secret

When making a request, it concatenates the request parameters with the secrets, and hashes the result

This hash is sent with the request, and checked by the server

e.g., imagine a GET request for /products/widgets

Let's say the client secret is "OH_HAI_I_IZ_SECRET"

Concatenate the HTTP verb, and the URL, and the secret:

GET/products/widgetsOH_HAI_I_IZ_SECRET

And take an SHA-1 hash of that:

4156023ce06aff06777bef3ecaf6d7fdb6ca4e02

Then send that along, so the request would be for:

GET /products/widgets?hash=4156023ce06aff06777bef3ecaf6d7fdb6ca4e02

Finally, to prevent someone from at least replaying individual requests, take a timestamp also, and add that to the parameters and the hash. e.g. right now, in Unix time, is 1384987891. Add that to the concatenation:

GET/products/widgetsOH_HAI_I_IZ_SECRET1384987891

Hash that:

2774561d4e9eb37994d6d71e4f396b85af6cacd1

And send:

GET /products/widgets?time=1384987891&hash=2774561d4e9eb37994d6d71e4f396b85af6cacd1

The server will check the hash and also verify that the timestamp is current (e.g. within 5 minutes to allow for clocks not being perfectly in sync)

Warning! Since you're talking about mobile apps, there's a definite risk that someone's phone will have it's clock wrong. Or timezone wrong. Or something. Adding the time to the hash will probably break some legit users, so use that idea with caution.


答:
Ok, so its worth mentioning before I start that for most applications this is hugely overkill. For most use cases simply having a single valid certificate and/or token is more than enough. If it involves doing anything hard like decompiling your app then even most hackers wont bother unless you provide some very valuable data. But hey, wheres the fun in that answer?

So what you can do is set up asymmetric cryptography somewhat like digital signatures used to sign programs. Each app can then have an individual certificate that is issued by a single CA and verified when your user connects. (either when first registering or when first installing) When that certificate is authenticated you can then further secure your application by registering that certificate as valid for one given device identifier (such as  Android ID)


问:
Is storing stack traces in database recommended?
The current system I am working on goes through a set of documents & performs some logic using the metadata of the document. If the metadata of a document is fishy..it throws an exception. The system logs the exception, fail the job & let the developer fix the issue by looking at logs before moving on.

I want to improvise this system by making system fault tolerant as I have seen that generally the job fails because of few documents. System continues even if there's an exception raised. The exception information would be stored in the database table along with document information. This information would be sent to developer who can then work on fixing it without having customer waiting. The customer can later process those failed documents separately.

My question is how to store the exception information in table. The exception would already be logged in the log file. One idea I was thinking was to store the time stamp of the exception so that developer can later find the time stamp in log file and understand the exception. But this comes with a possibility that the log files might be deleted.

Does it make sense to store the entire stack trace in the database?

答:
Yes. Storage is cheap.
It probably won't be accessed much (verify) or see a large number of records (verify as well).

One possible concern would be security, if access to the DB isn't as well protected as access to the log: can someone get undesired access to the traces, and from them obtain information that helps them compromise something else?


答:
To answer your question, you need to answer this:

Does the stack trace provide useful, additional diagnostic information that the exception itself doesn't have?

If yes, then sure, go ahead and store the stack trace information.

If no, then don't waste your time.

As to how to store the stack trace, there's all sorts of methods that you can consider.  For example, it's fairly trivial to create a routine that converts the stack information into strings and then store those strings.  Likewise, you could pull whatever additional arguments are on the stack and push those into the strings that you're creating.  It all depends upon what information you need.

More broadly, you should log information that helps you diagnose and resolve issues.  Whether you store that in a log file or a database is somewhat immaterial.  The point is that you're trying to record the error information when the error occurs.

If you're worried that the error information won't persist with whatever mechanism you chose (aka your logfile got deleted) then you need to come up with a more robust persistence mechanism for the error information.  But that problem is a separate issue from whether or not you should log XYZ information about an error.

Title: Is storing stack traces in database recommended?

Body:
The current system I am working on goes through a set of documents & performs some logic using the metadata of the document. If the metadata of a document is fishy..it throws an exception. The system logs the exception, fail the job & let the developer fix the issue by looking at logs before moving on.

I want to improvise this system by making system fault tolerant as I have seen that generally the job fails because of few documents. System continues even if there's an exception raised. The exception information would be stored in the database table along with document information. This information would be sent to developer who can then work on fixing it without having customer waiting. The customer can later process those failed documents separately.

My question is how to store the exception information in table. The exception would already be logged in the log file. One idea I was thinking was to store the time stamp of the exception so that developer can later find the time stamp in log file and understand the exception. But this comes with a possibility that the log files might be deleted.

Does it make sense to store the entire stack trace in the database?


问:
Confusion with gpl license
I am really confused about software linceses, I've read a lot of articles but I can't find an answer to my question, which is:
Can I develop and sell applications that uses libraries under gpl license? Like for instance, I want to use agsXMPP library in a windows phone app, and sell it in the market, so is it legal?</p>

答:
Your question is easily answered.  Just read the FSF FAQ on the GPL.  I linked to the FAQ that directly answers your question.

Does the GPL allow me to sell copies of the program for money?

Yes, the GPL allows everyone to do this. The right to sell copies is part of the definition of free software. Except in one special situation, there is no limit on what price you can charge. (The one exception is the required written offer to provide source code that must accompany binary-only release.)

Title: Confusion with gpl license


答:
Given your two examples, I always do the second one, but never the first.

```<code>function Foo() {
    this.bar = undefined;
    ....
}
</code>```

This creates an explicit list of properties available at a glance for maintenance purposes.1  It's equivalent to declaring public members in class-based object oriented languages:

```<code>class Foo:
    def __init__(self):
        self.bar = null;
</code>```

Relying on the default undefined in Javascript is similar to using setattr to create dynamic properties in Python - you can do it, and it's the right solution in some rare cases, but it's not going to help the maintainers.

1I don't use null for this, because sometimes null is a valid value - checking if a property is null or undefined tells me if it got initialized at all before being used somewhere.

Title: Initializing a variable as undefined

Body:
Doing some refactoring, I noticed an unusual pattern I'm not familiar with. Properties and variables that do not yet have a value are initiated with undefined declared explicitly, despite the fact that value-less variables and object properties would evaluate to undefined anyways:

```<code>var foo = undefined;
this.prop = undefined;
</code>```

Is there a reason to do this?

Body:
Given your two examples, I always do the second one, but never the first.

function Foo() {
    this.bar = undefined;
    ....
}

This creates an explicit list of properties available at a glance for maintenance purposes.1  It's equivalent to declaring public members in class-based object oriented languages:

class Foo:
    def __init__(self):
        self.bar = null;

Relying on the default undefined in Javascript is similar to using setattr to create dynamic properties in Python - you can do it, and it's the right solution in some rare cases, but it's not going to help the maintainers.

1I don't use null for this, because sometimes null is a valid value - checking if a property is null or undefined tells me if it got initialized at all before being used somewhere.


问:
How do I get people to stop bikeshedding (focusing on trivialities)?
I have been tasked with teaching other teams a new codebase, but I keep running into an issue. Whenever I go to actually walk through the code with people, we don't get very far before the entire exercise devolves into a bikeshedding (members of an organisation giving disproportionate weight to trivial issues) exercise. Since they don't know the codebase, but think they need to help improve it, they focus on the things they can understand:

Why is that named that?
(2 minutes to explain why it's named that, 10+ minutes debating a new name)

Why is that an abstract base class rather than an interface? (2 minutes to explain, 10+ minutes debating the relative merits of this decision)

...and so on. Now, don't get me wrong - good names and good, consistent design are important, but we never get to discussing what the code actually does or how the system is designed in any meaningful way. I've done some meeting refereeing to get people out of these tangents, but they're gone - distracted by what the code will/should be when their pet triviality is fixed, and they miss the bigger picture.

So we try again later (or with a different part of the codebase) and since people didn't get enough knowledge to overcome the bikeshedding effect, it repeats.

I've tried smaller groups, bigger groups, code, whiteboarding, visio diagrams, giant walls of text, letting them just argue it to death, cutting arguments short immediately... some help more than others, but nothing works. Hell, I even tried having other people from my team explain it because I thought it might be that I'm just bad at explaining things.

So how do you educate other programmers enough that they stop fixating on trivialities and can meaningfully contribute to the design?

答:
Have you tried making pre-lessons that people look over individually?

Make short videos or presentations that explain the content, how the code works, or basically all that you want to teach them in a format where they need to look at it on their own and learn the information you are trying to teach them.

Then you use the team-based sessions to discuss issues related to the content. You need to distinctly identify that the team sessions are for discussing and troubleshooting issues related to the content only.

If you provide the lessons to people on an individual basis, you may be able to avoid that other social issue where a single matter can become the voice of the group as a collective and distract away from the actual purpose of the lessons.


答:
I think the problem is the task: "I have been tasked with teaching other teams a new codebase".

You have been given the wrong job, or maybe misinterpreted the job you've been given.

By presenting at the code level, you invite code level thinking.

Start at the system level and present the design and the design choices that were made. Don't allow extended discussion: you are not reviewing it. Do allow questions: you do want them to understand the system. If people "would have done it differently", fine. Maybe agree. Or not. But move on. It's the way it is right now.

When you get to the code level, you will have already got them primed with the system terminology. The names (I assume) will make sense. Same as above: no extended discussion, questions for understanding. Move on.

Now set some class problems to work through. How can we make enhancement X? Choose something non-trivial that "goes with the flow" of the system design, and work through what you would change. They should be getting the rationale of the system now. Choose another enhancement that could break the system if done wrong, and show how it can be done right. That should be an Ah Ha moment for them. Some might even beat you to it!

It's a tough gig, especially after the false start you've had. Sounds like you've invested a lot of time and effort already, and maybe there is a bit of a me versus them feeling. 'Fess up, and start again. We assume that they are smart people. Give them the challenge of thinking at the higher level. And break up the groups that already exist by selecting different cross sections of teams for the new sessions.

Title: How do I get people to stop bikeshedding (focusing on trivialities)?

Body:
I have been tasked with teaching other teams a new codebase, but I keep running into an issue. Whenever I go to actually walk through the code with people, we don't get very far before the entire exercise devolves into a bikeshedding (members of an organisation giving disproportionate weight to trivial issues) exercise. Since they don't know the codebase, but think they need to help improve it, they focus on the things they can understand:

Why is that named that?
(2 minutes to explain why it's named that, 10+ minutes debating a new name)

Why is that an abstract base class rather than an interface? (2 minutes to explain, 10+ minutes debating the relative merits of this decision)

...and so on. Now, don't get me wrong - good names and good, consistent design are important, but we never get to discussing what the code actually does or how the system is designed in any meaningful way. I've done some meeting refereeing to get people out of these tangents, but they're gone - distracted by what the code will/should be when their pet triviality is fixed, and they miss the bigger picture.

So we try again later (or with a different part of the codebase) and since people didn't get enough knowledge to overcome the bikeshedding effect, it repeats.

I've tried smaller groups, bigger groups, code, whiteboarding, visio diagrams, giant walls of text, letting them just argue it to death, cutting arguments short immediately... some help more than others, but nothing works. Hell, I even tried having other people from my team explain it because I thought it might be that I'm just bad at explaining things.

So how do you educate other programmers enough that they stop fixating on trivialities and can meaningfully contribute to the design?


答:
Set expectations correctly and be honest, open and upfront.

Make sure your goals are open and transparent.

Start off discussions with the high level view as promoted by andy256 (+1) but also make sure that you include your objectives, e.g.

"...as we look at this issue, lets make sure we don't focus on x, y and z.  Let also make sure that we're not looking at at implementation details such as a,b,c or trivial details such as j,k,l.  I know there's bound to be a lot of details in the code and details things that could be addressed, improved or made more standard, but lets try and look at what it's really achieving at a higher level first"


答: "Park them". At the start of the lesson, explain what you are to discuss, and clearly explain what is considered Off Topic. If you are asked a question that is clearly OT, say so and move on. If they come back to it, write the question on a whiteboard (This is critical) for later discussion and move on. At the end of the lesson, when they are on their own time, not yours, watch how quickly those questions get resolved. </p>


问:
Separation of concerns and security
The system I am developing is designed to have multiple organizations, with users and roles for each organization.  Some organizations can interact, some can not, and generally organizations are not allowed to see or modify each others data with some exceptions.

I have a model class A that manipulates the data storage in a permanent storage container of some kind.  I have a controller class B that validates input (including access rights verification) to objects of class A.

The controller classes are in a separate library from the model classes.

All user interaction is performed from view classes which are again in a separated library (in this case exposed as web services).

However, it seems that there is a possible security risk in keeping access control logic separate from the model, since no security checks will be performed if the model is not accessed by its associated controller and is accessed instead by some other code due to some malicious attacker or programmer error.

Should I place the security logic in the same model classes weaving these concerns together or should I keep the separation as I have now?

答:
IMO, your instincts are good. To me it's basic, duh OOP, to put some kind of access-control on the class/object that controls the data. That data-controlling unit might do something as simple as telling the asker to go validate itself somewhere else and provide valid credentials if you feel validation logic needs to be split out but IMO, it is much more secure in the long haul that access control is at least initiated from the object that hands out the potentially sensitive data before doing so.

If you split it out, there's greater risk of somebody re-using code or making modifications and simply assuming it's being handled in some other fashion they might be used to dealing with. Or they might simply not care. Putting that call for validation on that data-managing object forces them to at the very least prove they don't care by disabling the call for validation and leaving evidence of that in source control.

It's okay for classes to get a little big as long as they're serving said class's purpose. I've seen far too many codebases busted into 10,000 1 or 2 method classes which is really no different than 10,000 functions in old-school badly-designed procedural code, which OOP is meant to help people improve on. Line-count doesn't matter if you're isolating responsibilities according to design so you don't potentially have thousands of hands on the same persistent data (real fun for debug) or an infinite number of ways for some crummy outsourced outfit to expose confidential data by accident long after you've left that codebase behind.

Title: Separation of concerns and security


答:
I think the Application you're building must be fairly uncomplicated, or else you're relatively early in its lifecycle. The only other scenario I can think of where you wouldn't have already run into problems with your statics is if you've managed to limit the other parts of your code that know about your Factory to one or two places.

Imagine that your Application evolves and now in some instances you need to produce a FooBar (subclass of Foo). Now you need to go through all places in your code that know about your SomeFactory and write some kind of logic that looks at someCondition and calls SomeFactory or SomeOtherFactory. Actually, looking at your example code, it's worse than that. You plan on just adding method after method for creating different Foos and all your client code has to check a condition before figuring out which Foo to make. Which means all clients need to have an intimate knowledge of how your Factory works and they all need to change whenever a new Foo is needed (or removed!).

Now imagine if you just created an IFooFactory that makes an IFoo. Now, producing a different subclass or even a completely different implementation is child's play--you just feed in the right IFooFactory higher up the chain and then when the client gets it, it calls gimmeAFoo() and will get the right foo because it got the right Factory.

You might be wondering how this plays out in production code. To give you one example from the codebase I'm working on that's starting to level out after just over a year of cranking out projects, I have a bunch of Factories that are used to create Question data objects (they're something like Presentation Models). I have a QuestionFactoryMap that's basically a hash for looking up which question factory to use when. So to create an Application that asks different questions, I put different Factories into the map.

Questions can be presented in either Instructions or Exercises (which both implement IContentBlock), so each InstructionsFactory or ExerciseFactory will get a copy of the QuestionFactoryMap. Then, the various Instructions and Exercise factories are handed to the ContentBlockBuilder which again maintains a hash of which to use when. And then when the XML is loaded in, the ContentBlockBuilder calls up the Exercise or Instructions Factory out of the hash and asks for it to createContent(), and then the Factory delegates the building of the questions to whatever it pulls out of its internal QuestionFactoryMap based on what is in each XML node vs. the hash. Unfortunately, that thing is a BaseQuestion instead of an IQuestion, but that just goes to show that even when you're being careful about design you can make mistakes that can haunt you down the line.

Your gut is telling you that these statics will hurt you, and there's certainly plenty out there in the literature to support your gut. You will never lose by having Dependency Injection that you wind up only using for your Unit Tests (not that I believe that if you build good code that you won't find yourself using it more than that), but statics can completely destroy your ability to quickly and easily modify your code. So why even go there?

Title: Static factory vs factory as a singleton

Body:
In some of my code, I have a static factory similar to this:

```<code>public class SomeFactory {

    // Static class
    private SomeFactory() {...}

    public static Foo createFoo() {...}

    public static Foo createFooerFoo() {...}
}
</code>```

During a code review, it was proposed that this should be a singleton and injected.  So, it should look like this:

```<code>public class SomeFactory {

    public SomeFactory() {}

    public Foo createFoo() {...}

    public Foo createFooerFoo() {...}
}
</code>```

A few things to highlight:

Both factories are stateless.

The only difference between the methods are their scopes (instance vs static).  The implementations are the same.

Foo is a bean that does not have an interface.

The arguments I had for going static was:

The class is stateless, therefore doesn't need to be instantiated

It seems more natural to be able to call a static method than to have to instantiate a factory

The arguments for the factory as a singleton was:

Its good to inject everything

Despite the statelessness of the factory, testing is easier with injection (easy to mock)

It should be mocked when testing the consumer

I have some serious issues with the singleton approach since it seems to suggest that no methods should ever be static.  It also seems to suggest that utilities such as StringUtils should be wrapped and injected, which seems silly.  Lastly, it implies that I'll need to mock the factory at some point, which doesn't seem right.  I can't think of when I'd need to mock the factory.

What does the community think?  While I don't like the singleton approach, I don't seem to have a terribly strong argument against it.


问:
What are the set of skills that every programmer graduating from college should have?
We had a guest lecturer at our school he went on a tangent regarding those graduating and not being upto the skill level he expects ie. knowledge of one big-time compiled languague like Java, C++ or C#, one scripting language like Python or Ruby, one web framework. What are some other skills that you guys think should be absolutely critical to graduating student?</p>

答:
New graduates need more than just a desire to learn, they need an obsession of learning, an understanding of how to learn, and a firm grounding in the realities of software. I generally don't care what languages you know, but every junior must:

Understand history. Computer science is a well researched field, with many solved problems. Knowing this fact opens the door to learning from what's come before you. Even knowing that there is a rich history to mine knowledge from is more than many graduates grok. This includes things like big-O notation, history of algorithms, principles of the prophets (Knuth, K&R, Hofstdater, etc.), and commonly accepted practices and patterns.

Know that it can be solved. I am always surprised when a developer is stumped by a problem. Part of learning to learn is the simple principle that problems are easily soluble, always. Once you know this, it frames your thinking for finding a sane answer.

Understand decomposition. Not only can problems be solved, but the path to doing so is as simple as divide and conquer. Reduce a problem down to simpler components, and your answer will always present itself.

Know how to measure. In addition to being able to decompose problems, new developers need to know how to gather facts about these problems. How long? How large? How fast? How many? Simple facts are a step to understanding and objective thinking. Making assumptions without facts is an easy way to get lost in the problem space.

Be objective. All problems can be decomposed, measured, and understood simply. The problems that can't be understood simply merely require additional decomposition, measurement, and understanding. There is no use in getting angry or frustrated, nor is it productive to argue about theories or place blame. Any irrational behavior or belief related to the process of solving problems is poison, making solutions very difficult to find.

Prefer patterns and principles. You will encounter dozens of right ways to do things, languages, programming models, computer architectures, and even engineering methods. There is no single right way, but there are solid underlying concepts that you can apply over and over again. Learn to see these patterns, as they will guide your learning and thinking every step of the way.

OwnerDisplayName: Wallz

ContentLicense: CC BY-SA 2.5


问:
Selecting a software license for a blog posting in CodeProject.com
I am planning to post an article on codeproject.com where I will be sharing some code I feel worthy of the effort - so I went and read the posting guidelines. It appears that I will have to select a software license for my submission. I really do not care about my material and what people will do with the code that I will give. If they profit from it that is all fine with me and I am happy to have shared my ideas. My concern really is more about my own personal protection that if the code I give for some remotest of reasons inflict damage to them or to their system that I should not be liable for anything. Or something to that effect.

My material is about patterns for ASP.NET CRUD operations. I use this pattern every single project that I have. It is absolutely harmless, but you never know really how other people will use it. I just want to have some safety net.

What license is suitable for me in this situation?

答:
Just about all open source licenses come with a liability disclaimer that try to limit the liability of the copyright holder to the maximum extent possible.
In how far you can actually limit your liability depends on the local laws of where the software gets used.

As there is no real difference in the liability disclaimers, all open source licenses are a good fit in that respect. As you indicate you don't really care how your software gets used, the BSD (2 clause or 3 clause) and MIT licenses would meet that as well.


问:
Terminating a freelance contract before completion
I've been building a large web application for a company. Initially the project owner appointed a Graphic/Web designer to complete all design/front end works. Me and who ever I bring in to complete back end and all the view binding at the front.

The initially front end/graphics guy dropped out and was replaced with a (better) graphic designer who ISN'T producing the html/css required. This deficit caused many months of overrun with me having to try to introduce front end devs to complete the missing pieces.

On top of that, numerous articles of the initial spec have been changed and several items added.

A month or so ago after receiving an incredibly aggressive phonecall from the project owner decided I was no longer interested in being involved in the project. Obviously all the source code, all documentation etc belong to the client for them to bring in another party.

I at this point had been paid 2/3 of the agreed sum. Also shouldered hosting costs myself.

The clients response was immediately to threaten me with legal action claiming I'd be breaching our contract by not completing and that I had already breached our contract by running over on delivery dates. He also stated that he felt it would be impossible to replace me on the project because of the obscure technology I'd selected to build it (ASP.Net MVC). He suggested he would intend to attempt to recoup all monies paid so far and damages that he "calculates" (see:made up) to be about £70k.

I do a lot of work for a company who's MD is a corporate lawyer. Who's confirmed that technically both parties are in breach of contract, but that's justified by the unforeseen changes in replacing designers etc...

I've continued working to now.

My (a little long-winded) question is morally and practically what would you do? I'm owed 1/3 of the remaining contract and hosting fees. (about £3500 total) They have lined up another .Net dev to build on the out of spec items as I've stated they're not my responsibility.
The site is just undergoing bug/acceptance testing/fixing which the client doesn't believe they should have any involvement in.
Should I stick around for the cash, which also ties me into any corrective maintenance for 2 months. Or do I write it off as a "make sure to re-agree terms when big things change" lesson?

答:
You should always consider your reputation in situations like these. If you want to get more work from the same company, sounds unlikely, but a good reference might be more helpful.

Your MD lawyer sounds right, but it does depend on what you have said in the termination section of your contract. I typically have 30 days notice, but in some cases I have 10 days.

A paying client is also a generally a good client, and you must understand that the Project Owner is probably under a lot of pressure too. So, as long as they are paying you I would try to negotiate a more suitable contract.

I would look into drafting and signing a new contract that reflects the current situation, defining the new milestones and responsibities, and adjusting time lines. Also look at putting a "Professional Responsibility and Conduct" section into this contract, stating how you expect your client to treat you, with respect and curtsey, etc...and you will do the same. I have found this useful, when you land up with a very pushy PMs. Don't forget "Change Management" section.

I would also state in this new contract, which milestones I would expect the client to achieve, focusing on what is needed from them to successfully complete the project (in time). I will also hold then accountable to meeting these objectives, such as "hiring" suitably skilled graphics designers in time. I would kick up a fuss when the don't deliver too. In  business, its always good to be diplomatic and try to negotiate things before getting "legal" - that gets expensive, quickly, and everyone losses out.

Of course, if I was unable to negotiate a new contract, I would hand my "official" notice in, stating the inability of either party to come to mutually suitable agreement as well as the outlining the "issues" in the projects track record, as the key factors for the termination.

Hope that helps.


问:
When does one NOT need to use queues in an application?
I've been developing an application using the Laravel Framework & have been exposed to the idea of queues for the first time. There are a multitude of tutorials & articles about using queues & examples of what to use for, but I've never seen anyone writing about or highlighting when one does not need to actually use any.

I've seen examples or even forum questions about using say beanstalked or iron.mq for offloading jobs that then take place in a managed manner, I understand the concept; but is there a need to make use of queues if say my application makes use of a mailing service like Postmark or Mandrill? Is there a benefit in that case?

I mean I've tested both & obviously they both queue jobs on their service to allow their service to function; do I need a queue for email when I'm offloading the act of mailing to a service detached from my application. ( my application has not been released into the wild, I do not actually have benchmark type information at present )

How different is giving jobs to ironmq (which still calls an api and sends data) to making a call to say Mandrill by sending data? More to the point; does one need to have a queue like using iron.mq  to send mail requests to mandrill which happens to queue stuff too?

答:
One of the advantages of using explicit queues, is that you can try again if the receiving system is down for some reason.

Also if there's something wrong with the message you're putting on a queue (as far as the receiving system is concerned), you can have it be put on an error queue, where you can manually fix the message and resend it.

It's all a question of whether or not you have a need for the aforementioned benefits.


问:
Open Source but not Free Software (or vice versa)
The definition of "Free Software" from the Free Software Foundation:

“Free software” is a matter of
  liberty, not price. To understand the
  concept, you should think of “free” as
  in “free speech,” not as in “free
  beer.”

Free software is a matter of the
  users' freedom to run, copy,
  distribute, study, change and improve
  the software. More precisely, it means
  that the program's users have the four
  essential freedoms:

The freedom to run the program, for
  any purpose (freedom 0).

The freedom
  to study how the program works, and
  change it to make it do what you wish
  (freedom 1). Access to the source
  code is a precondition for this.

The
  freedom to redistribute copies so you
  can help your neighbor (freedom 2).

The freedom to distribute copies of
  your modified versions to others
  (freedom 3). By doing this you can
  give the whole community a chance to
  benefit from your changes. Access to
  the source code is a precondition for
  this.

A program is free software if users
  have all of these freedoms. Thus, you
  should be free to redistribute copies,
  either with or without modifications,
  either gratis or charging a fee for
  distribution, to anyone anywhere.
  Being free to do these things means
  (among other things) that you do not
  have to ask or pay for permission to
  do so.

The definition of "Open Source Software" from the Open Source Initiative:

Open source doesn't just mean access
  to the source code. The distribution
  terms of open-source software must
  comply with the following criteria:

Free Redistribution The license shall not restrict any party from
  selling or giving away the software as
  a component of an aggregate software
  distribution containing programs from
  several different sources. The license
  shall not require a royalty or other
  fee for such sale.

Source Code The program must include source code, and must allow
  distribution in source code as well as
  compiled form. Where some form of a
  product is not distributed with source
  code, there must be a well-publicized
  means of obtaining the source code for
  no more than a reasonable reproduction
  cost preferably, downloading via the
  Internet without charge. The source
  code must be the preferred form in
  which a programmer would modify the
  program. Deliberately obfuscated
  source code is not allowed.
  Intermediate forms such as the output
  of a preprocessor or translator are
  not allowed.

Derived Works The license must allow modifications and derived works,
  and must allow them to be distributed
  under the same terms as the license of
  the original software.

Integrity of The Author's Source Code The license may restrict
  source-code from being distributed in
  modified form only if the license
  allows the distribution of "patch
  files" with the source code for the
  purpose of modifying the program at
  build time. The license must
  explicitly permit distribution of
  software built from modified source
  code. The license may require derived
  works to carry a different name or
  version number from the original
  software.

No Discrimination Against Persons or Groups The license must not
  discriminate against any person or
  group of persons.

No Discrimination Against Fields of Endeavor The license must not restrict
  anyone from making use of the program
  in a specific field of endeavor. For
  example, it may not restrict the
  program from being used in a business,
  or from being used for genetic
  research.

Distribution of License The rights attached to the program must apply to
  all to whom the program is
  redistributed without the need for
  execution of an additional license by
  those parties.

License Must Not Be Specific to a Product The rights attached to the
  program must not depend on the
  program's being part of a particular
  software distribution. If the program
  is extracted from that distribution
  and used or distributed within the
  terms of the program's license, all
  parties to whom the program is
  redistributed should have the same
  rights as those that are granted in
  conjunction with the original software
  distribution.

License Must Not Restrict Other Software The license must not place
  restrictions on other software that is
  distributed along with the licensed
  software. For example, the license
  must not insist that all other
  programs distributed on the same
  medium must be open-source software.

License Must Be Technology-Neutral No provision of the license may be
  predicated on any individual
  technology or style of interface.

These definitions, although they derive from very different ideologies, are broadly compatible, and most Free Software is also Open Source Software and vice versa. I believe, however, that it is possible for this not to be the case: It is possible for software to be Open Source without being Free, or to be Free without being Open Source.

Questions

Is my belief correct? Is it possible for software to fall into one camp and not the other?

Does any such software actually exist? Please give examples.

Clarification

I've already accepted an answer now, but I seem to have confused a lot of people, so perhaps a clarification is in order. I was not asking about the difference between copyleft (or "viral", though I don't like that term) and non-copyleft ("permissive") licenses. Nor was I asking about your personal idiosyncratic definitions of "Free" and "Open". I was asking about "Free Software as defined by the FSF" and "Open Source Software as defined by the OSI". Are the two always the same? Is it possible to be one without being the other?

And the answer, it seems, is that it's impossible to be Free without being Open, but possible to be Open without being Free. Thank you everyone who actually answered the question.

答:
It is possible for software to be "Open Source" but not "Free Software" (free in etiher sense)

The reverse I think is not possible, Freedom 1 requires Source Code.


问:
Visual Studio versions and Team Etiquette
I have a project on CodePlex that I have opened to basically anyone to join and help out on. I am mostly an enthusiast coder, although I have done some programming work as part of my job it has always been solo projects that my team uses for IT support.

With my CodePlex project, I got my first new fork yesterday. I cloned it to see some of the changes and realized he had upgraded the package to VS 2012 from my 2010.

What is team etiquette for Visual Studio in a team environment? I can see the benefit of using the latest and greatest, but forcing the hand of a team to upgrade seems a little off too.

My assumption is this developer did not consider it.

Is it considered good etiquette to maintain a standard, even if outdated like with VS 2010? Or is the best etiquette to use the latest stable Visual Studio, and those with out an upgrade can use the Express versions of the latest? Or is there a standard way to make a solution IDE agnostic between VS versions?

Edit

A ton of great input. And the verdict seems to be there is no universal or established etiquette. That it really boils down to my own preferences for the project and what affect the change has on the project.

答:
VS 2012 is capable to work with VS 2010 projects in their format, without forcing you to upgrade. So if you don't want get excluded, and don't want to exclude other developers who are not willing or able to upgrade to VS 2012 (at least not now), and as long as there is no real benefit of using the VS 2012 format in your project, you should encourage everyone to keep projects in the older format (especially, if that is the VS version you are working with). For example, put a "readme" file beside the solution file where you explain your wishes.

In fact, if someone else is willing to maintain a VS 2012 project file in parallel to your VS 2010, you can't hinder them from that, but as you are the author and maintainer of the project, it would be at least polite for your contributors to respect your wishes as long this does not mean extrordinary efforts for them.

On the other hand, when the next VS version brings you and your contributors some  benefits like noticeable productivity increasements, and these benefits are ony available for the drawback of an incompatible project format, then IMHO you should consider to upgrade as soon as possible.


答:
By definition, he has forked the project. He hasn't forced anything on "the team".... yet.

He has taken his own copy, and for whatever reason, upgraded it.

Maybe at some point he would like to request that it is merged back into the main project, but that would then have to be approved by you/the team.

Title: Visual Studio versions and Team Etiquette

Body:
I have a project on CodePlex that I have opened to basically anyone to join and help out on. I am mostly an enthusiast coder, although I have done some programming work as part of my job it has always been solo projects that my team uses for IT support.

With my CodePlex project, I got my first new fork yesterday. I cloned it to see some of the changes and realized he had upgraded the package to VS 2012 from my 2010.

What is team etiquette for Visual Studio in a team environment? I can see the benefit of using the latest and greatest, but forcing the hand of a team to upgrade seems a little off too.

My assumption is this developer did not consider it.

Is it considered good etiquette to maintain a standard, even if outdated like with VS 2010? Or is the best etiquette to use the latest stable Visual Studio, and those with out an upgrade can use the Express versions of the latest? Or is there a standard way to make a solution IDE agnostic between VS versions?

Edit

A ton of great input. And the verdict seems to be there is no universal or established etiquette. That it really boils down to my own preferences for the project and what affect the change has on the project.


问:
How to implement loose coupling?
I want to implement loose coupling in a project.

I know two examples of successful loose coupling designs:

On a Unix workstation, shell scripts realise a loose coupling between basic utilities. The loose coupling relies on the shell's ability to blindly redirect data flows between utilities, without having any knowledge on the structure.  Utilities agree on a common form to cooperate like a pipe-separated format for sort, cut, paste, awk, etc., a svn dump or a trivial dump of a normalised SGML document (with onsglmls).

On a Mac OS X system, Applescripts can be regarded as a loose coupling.

In these two examples, I see that cooperating components agree on a common protocol to serialise and deserialise data that needs to be exchanged. Thus components depend on the serialisation protocol rather than on internal representation of data.

Is the implementation of a stable communication protocol between application components a winning strategy to implement loose coupling (and good encapsulation)?

To solve ties, I also ask what would be a nice name for the protocol artefacts: “data” is a bit vague and there is a lot of them at various places in a software!

答:
First of all, it isn't correct to say "implement loose coupling". Loose coupling is a design principle, and a principle can be applied but not implemented. That being said, you can apply that principle to any project you like.

Regarding the examples, IMO they're samples of design by contract. The components agree upon an interface or protocol through which they can interact. While the components may change their internal structure or logic, the interface of interaction remains the same.

It is fair to say that design by contract is a sample of applying loose coupling. But the implication of loose coupling isn't limited to design by contract only. It can be applied to any project to keep the pieces as independent as possible.

I think you might be interested in measuring coupling and cohesion and Demeter's law and it's relation to coupling.

Title: How to implement loose coupling?


问:
Would using rainbow tables to detect weak user passwords feasible?
As I understand in most security breach where the list of hashed password are compromised, attackers do use brute-force to try to find weak password and, invariably, they always find quite some (like in the recent Github breach).

If I'm not mistaken in most cases when a user creates an account, the password is sent, encrypted (due to TLS / SSL), to the website which then adds some salt and stores the hash + salt.

Even in most sophisticated cases (like when bcrypt is used), upon account creation there's one point in time at which the server does have the password in cleartext.

My question is: couldn't you use, at that very moment when you have the password in the clear that the user is trying to use for his new account, a gigantic rainbow-table on the server side to check for billions and billions of weak passwords in a split-nanosecond?

Then if you detect that a weak password is used, you'd simply tell to the user that his password is too simple and that, no, using "edcrfvtgb1" isn't smart.

I mean: if attackers manage to brute-force weak-password even though they have to deal with the problem of the salt, couldn't servers benefit from the fact that, when the users creates a new account, they do know the password in the clear to simply look it up in a big rainbow table when the user creates his account?

This doesn't seem hard to implement and seen harddisk sizes these days, it's probably not problematic to store a big rainbow table on the server side.

Am I missing something obvious or would this help catch a lot of weak passwords and, hence, mitigate the endless accounts compromise we keep seeing on a nearly daily basis?

答:
TL;DR - yes & no.  Yes it can be done but no, it shouldn't be done as you suggest.

My question is: couldn't you use, at that very moment when you have the password in the clear that the user is trying to use for his new account, a gigantic rainbow-table on the server side to check for billions and billions of weak passwords in a split-nanosecond?

No, you can't - or at least, not as you suggested.

To make the approach you suggested viable would require compromising the security of the site.  And there's better ways to accomplish what you want to do.

Why? The problem is a misunderstanding with how rainbow tables work.  And here are the issues.

A rainbow table is precomputed

A the salt added to a new user's password for hashing should be random

A good salt will be at least 10 - 16 characters long (see 1, 2, 3), which will add ~80-128 bits more of entropy to the overall password.  Even with a 10 character salt and an 8 character password (both weak), that's 2.2 x10^43 potential combinations.  A rainbow table with that many combinations would require more disk space than most can afford.

If you used a fixed salt (which isn't recommended as it compromises the security), then you would be able to relatively easily build a rainbow table that could be used as you suggested.  But a fixed salt partially defeats the purpose of using a salt to begin with.

Rainbow tables are useful attack vectors when salts aren't used or when the salt is a fixed length.  Without a random salt, it's easy enough to take the hashed value from the password file and look up the cleartext password in the rainbow table.

Using random salts force an attacker to use brute force to crack the password.  There's just too many combinations to be stored to make a lookup approach worthwhile.  Technology advancements have also made brute force approaches more practical.  As of Dec 2012, some of the fastest GPU backed brute force password cracking systems could process 350 billion passwords per second.  (see here for reference)  With technology advancements, that rate will only increase.

Am I missing something obvious or would this help catch a lot of weak passwords and, hence, mitigate the endless accounts compromise we keep seeing on a nearly daily basis?

Yes, you're kind of missing something about rainbow tables but we just beat that subject into the ground with the above.

As I alluded to earlier, there are easier ways to do what you're suggesting.  They can even be done client side via javascript so you don't have to incur a roundtrip penalty for the server to tell the client / new user that their password is too weak.

Password vaults like KeePass* have a built in password entropy indicator.  Using the "edcrfvtgb1" password example that you provided, we see it only has 50 bits of entropy which is relatively weak.  Current recommendations are to have passwords with 98 to 128 bits of entropy depending upon how secure you need it to be.

You could use a javascript plugin that measures password entropy to provide immediate feedback to the new user or a user who is changing their password.  This link goes into some detail with actual code and also contrasts against older methods of handling passwords.  Running a web search against javascript password strength meter comes back with more than enough hits to kickstart additional research.

So your original thought is good, and yes the broader question that you are asking can be done.  From my observation, I have seen a number of sites start to incorporate password strength meters to help guide users in selecting passwords.

 * I just happen to know of KeePass, there are many other excellent password vaults out there that offer the same functionality.

... and the obligatory xkcd link.  Hat tip to Marjan Venema for posting it first in a comment.

So just how much data would that be?

10 bytes of salt + 8 bytes of password yields 144 bits.

2^144 is ~2.2x10^43 combinations.

Each combination will need at least 18 bytes for salt+password and 60 bytes for a bcrypt hash.  (see here)  For a total of (at least) 78 bytes per combination.

2.2x10^42 combinations * 78 bytes = ~1.7x10^45 bytes.

Shrinking that down a bit yields: 1,438,846,037,749,345,026,048 YB (yotta bytes)

Or perhaps we could call that 1.4 penta-yotta bytes.  I call it "a lot."


答:
If you are the maintainer for the original project, you should decide what version of dev tools (Visual Studio) you want to standardize on. You should communicate this decision somewhere visible on the project's website.

Then, if anyone submits a pull request that changes the VS project, and they moved away from the standard version, ask them to fix this before you merge their changes.

In the case of Visual Studio, it probably depends on what language you are using in your original project - if you use C++, you might want to consider to use VS2012 or VS2013, just because of the greatly improved C++11 support. If it's a C# project, unless you use async, you can probably keep everything on VS2010 to have the greatest compatibility.


问:
Dictionary of objects
I have a dictionary of Objects of a class Columns

```<code>Dictionary<double, Columns>
</code>```

Columns is a class of columns, i.e. name, post code, etc, mobile phone. I would like to make Columns class as much open for extension as possible, so it will be no trouble to add more classes. I need to set few of the columns to be there always, and would like the user to be able to define which columns to display from the remaining, and also add custom columns. Each columns has to have a method getValue()

My idea is to create an abstract class Column and derive specific columns from it. Make each child class implement the getValue() method by making it abstract what should force it to be overridden (am I correct?). I will define enum which will list all available column types. Finally, a class Columns would keep all the available columns in dictionary

```<code>Dictionary<enum, Column>
</code>```

My question is: is my thinking process correct? Is there any room for improvement? Would it be a better idea to use interfaces? Finally, is this design going to be efficient and fast for rapidly changing values in columns, i.e. within a second I might have to update 50 different records in this dictionary.

答:
I think you need to pause and reconsider what you're doing.  My preference is for the code to mirror the business problem that I'm trying to solve.  Defining your problem in terms of a language primitive and a complex object that mirrors a database element doesn't help me understand what you're trying to solve.

As mentioned by Heinzi, using a double for your key is probably unwise.  Consider an integer (which could represent a customer ID) or a string (which could represent a customer name) instead.  If speed / performance is of concern, I would probably use an integer but I wouldn't worry about it too much unless I benchmarked it both ways.

For the value, consider creating a class that makes sense for your problem.  You mentioned name, post code, etc, mobile phone. which made me think of "personally identifiable information" (PII) or "client contact information" (CCI) or something similar.  So I would build a class to that effect and use that as my value type instead.

If you had both a PII and a CCI class that could be stored, then I would consider an Interface and use that as the value type.  Using an enum or some other sort of flagging mechanism to indicate available data types is perfectly fine too.  If you use an Interface, consider putting the flag(s) inside of the Interface to enable additional access beyond the core Interface fields.

OwnerDisplayName: Macin

Title: Dictionary of objects


问:
Is there any work into the application of the Halstead complexity measures to determine software quality?
In 1977, Maurice Howard Halstead introduced his complexity measures for software systems, which included measurements of the program vocabulary, program length, volume, difficulty, effort, and an estimated number of bugs in a module. According to Wikipedia, difficulty relates to the difficulty of understanding the program when reading or writing it and effort can be translated into the time it takes to code an application where Time = (Effort / 18) seconds.

A measurement is useless unless the data and calculations relate to some aspect of software development. However, I haven't found any work which states that a difficulty of a certain value or higher tends to a statistically significant increase in defects or a relationship between difficulty and time to read code (a difficulty of N yields an average of M hours spent understanding the code base) or any analysis of being able to compute Time after the fact being useful in determining quality (especially since time to write should have been recorded as a measurement already). I'm especially interested in Halstead's bug estimation (which is not mentioned on Wikipedia) - the number of bugs in an application can be estimated by Volume/3000 or Effort^(2/3)/3000.

I'm looking for two things:

Has anyone used Halstead's software complexity measures in a real-world application to assess software quality? If so, how did you apply them and did they turn out to be a useful, valid, and/or reliable measurement?

Is there any academic research in the form of surveys, analyses, or case studies that discuss the validity (or invalidity) of Halstead complexity measures when applied to software quality?

Is there any academic research in the form of surveys, analyses, or case studies that demonstrate the use of Source Lines of Code (SLOC) to compute something similar to the Halstead metrics of Volume, Difficulty, Effort, Time, and Bugs? I would suspect that Volume might just correspond to a SLOC count and Difficulty might correspond to cyclomatic complexity (and possibly other measures). I'm also well aware that measuring effort, productivity, or time in SLOC is potentially misleading.

答: That Halstead Volume is correlated with SLOC is interesting but limited. Basic statistics: linear correlation is not transitive. X correlated to Y, Y correlated to Z DOES NOT MEAN that X is correlated to Z.</p>


问:
Object oriented parser model review
First time I make use of Code Review. At the moment I'm creating an Android application and the company I'm developing it for, has a specific file format that can be used to give text based data specific formatting rules. See it as an rich text format especially build and designed for their use.

The File format to work with

The file format was or at least is in my opinion designed to be used for pure formatting reasons and is actually not very well designed for data access. The Android application I'm writing depends very strongly on data access, that being said I had to design a smart parser which is capable of transforming the formatted text to some kind of data model which could still have the formatting included.

A typical file could exist out of 600 lines of text having a total of 60000 characters. And could look like this:

```<code>\id sit amet
\ide UTF-8
\rem File version: 2013-06-18
\rem Copyright 1995-2012
\t Lorem ipsum
\h 1
\st Nunc at urna
\p
\v 1 Lorem ipsum dolor sit amet, consectetur adipiscing elit.
\v 2 Suspendisse ac turpis quis diam elementum cursus sit amet non urna.
\pq Vestibulum vulputate \nd dui\nd* eget pharetra adipiscing.
\pq Suspendisse viverra metus quis feugiat rutrum.
\v 3 Nunc at urna vehicula, luctus quam convallis, adipiscing metus.
\v 4 Integer sit amet neque condimentum, laoreet neque ut, feugiat tellus.
\h 2
\v 1 Nam commodo orci et magna eleifend imperdiet.
\v 2 Cras a lorem ac nunc interdum lacinia.
\v 3 Integer vestibulum mauris id scelerisque lacinia.
\st Ut molestie nibh
\p
\v 4 Duis aliquam \nd diam\nd* nec nisl hendrerit posuere.
\v 5 Donec eget sapien id purus sollicitudin elementum non eget arcu.
\b
\v 6 Fusce auctor justo vitae aliquam luctus.
\v 7 Phasellus eget nisl at dui dignissim pharetra.
\v 8 Mauris iaculis mi at augue mattis, eu bibendum nunc placerat.
</code>```

The \h marker and the \v marker are the most important markers they are used to identify the data using the integer behind it. The other makers are mostly irrelevant (like the \id, \ide, \rem markers), and some like \pq are used to append their data to the line above it but with some formatting applied to it. And some markers are "in-text" like the \nd marker.

Of course there are a lot of rules how the tags can be used in a valid file, but it's totally irrelevant for the review I think. (Or is there someone willing to read 90 pages?)

The structure of the parser

So I came up with the following (Object oriented) parsing model:

The parser has to be:

Able to separate DATA from FORMATTING

Fast

separate the data and the formatting so both can be easily accessed

Able to parse a subset of data or a specific range of data from a file

A selection of data is often referred as: File - Level - Sub-level(actual data)

Where the file is just a file to parse, the level an integer which can be found in the file by the \h marker and the Sub-level just like Level with the \v maker.

The parser I wrote returns an object which holds two lists - one with all the formatting and one with all the data.

```<code>public class ParseResult {
    protected ArrayList<FileData> data = new ArrayList<FileData>();
    protected ArrayList<FileFormat> format = new ArrayList<FileFormat>();
}
</code>```

The FileData object and the FileFormat object can be extended to create numerous different formats and data objects. This is the structure I use in the parser I wrote:

For data:

```<code>FileData
    -FileDataLocation extends FileData
        -FileDataText extends FileDataLocation
        -FileDataThing extends FileDataLocation
    -FileDataAnotherThing extends FileData
</code>```

For formatting:

```<code>FileFormat
    -FileFormatLevel extends FileFormat
    -FileFormatTitle extends FileFormat
    -FileFormatSubLevel extends FileFormat
    -FileFormatSpecialTokens extends FileFormat
</code>```

To use data from the parsed file I use the data ArrayList. To print the data formatted I loop trough the format ArrayList which is sorted so that the beginning of the file would be at the 0 index of the list and the end of the parsed file the last index of the list.

Each formatting object has a reference to a data object in the data list. So that when using the formatting objects the data is always accessible. The formatting objects only hold information what peace of data the format should be applied to and what kind of formatting.

Parsing method

When parsing a file the parser reads the file line by line and constantly keeps track of the \h and \v markers, and starts capturing data in the ParseResult object when a specific combination of the markers is found (Lets call that a location).

To check what type of marker the parser is dealing with I scan the line until I find the first whitespace. When a whitespace has been found a substring can be made from the start of the line to the location of the whitespace.

Comparing the substring with a list of known makers tells the parser what to do with the line.

After the marker is found the line is processed using regex. This is an example regex for a line with the \v marker:

```<code>\v\s(([0-9]{1,3})(?:-([0-9]{1,3}))?)\s{1}(.+)[\n\r$]*
</code>```

Review?

The performance of the parser is not bad at all, the largest files take about 600ms to process completely (9000 lines, 280000 characters).

Things I would like to know

Data is now (after parsing) stored in just a list, searching for a specific peace of data is not very well optimized. Are there other structures I could use, which I can search using file(string) - level(integer) - sub-level(integer) so I can quickly get a specific data object.

When looping trough the formatting list I must check what instance an object belongs to, and then cast the object so I can use the specific methods and functions. Is there a better, other, alternative method?

The file format is pretty basic, should I consider removing all regex functions and parse it whole by just regular code?

答:
Data is now (after parsing) stored in just a list, searching for a specific peace of data is not very well optimized. Are there other structures I could use, which I can search using file(string) - level(integer) - sub-level(integer) so I can quickly get a specific data object.

Assuming that you want to search by File, Level, Sub-Level only, you have a clear hierarchical structure in that description, it sounds like you can divide one ArrayList into multiple steps. You could even make each hierarchy level a class itself to make it more clear, for example:

```<code>class SomeFileData {
   List<LevelData> levels;
}

class LevelData {
   List<SubLevelData> sublevels;
}

class SubLevelData {
   // Probably similar to your current `FileData` implementation
}
</code>```

And if you need to save multiple files at once, you can use a Map with the file name as key.

```<code>class LotsOfFileData {
    Map<String, SomeFileData> files;
}
</code>```

Using this hierarchy, you can easily get file "mydata.dat", level 3, sublevel 4.

```<code>LotsOfFileData allData;
allData.getFile("mydata.dat").getLevel(3).getSublevel(4)
</code>```

Each step in the get process looks at the current class' list or map to retrieve the data.

By the way, declare variables according to their interface, not their implementation. Declare your ArrayLists as List to allow for easy change of implementation.

OwnerDisplayName: Rolf Smit

Title: Object oriented parser model review

Body:
Data is now (after parsing) stored in just a list, searching for a specific peace of data is not very well optimized. Are there other structures I could use, which I can search using file(string) - level(integer) - sub-level(integer) so I can quickly get a specific data object.

Assuming that you want to search by File, Level, Sub-Level only, you have a clear hierarchical structure in that description, it sounds like you can divide one ArrayList into multiple steps. You could even make each hierarchy level a class itself to make it more clear, for example:

class SomeFileData {
   List<LevelData> levels;
}

class LevelData {
   List<SubLevelData> sublevels;
}

class SubLevelData {
   // Probably similar to your current `FileData` implementation
}

And if you need to save multiple files at once, you can use a Map with the file name as key.

class LotsOfFileData {
    Map<String, SomeFileData> files;
}

Using this hierarchy, you can easily get file "mydata.dat", level 3, sublevel 4.

LotsOfFileData allData;
allData.getFile("mydata.dat").getLevel(3).getSublevel(4)

Each step in the get process looks at the current class' list or map to retrieve the data.

By the way, declare variables according to their interface, not their implementation. Declare your ArrayLists as List to allow for easy change of implementation.

OwnerDisplayName: Simon André Forsberg


答:
In certain organization you are never going to be able to achieve this. Many organizations value political wrangling and ladder-climbing way more than intellectual capacity, diligence, and loyalty. And why wouldn't they. Ladder-climbing puts people in positions of power, allows them to enhance their personal lives with more discretionary income and really never becomes obsolete.

Contrast this power-wrangling with actual problem solving, abstract thinking, and making decision on tough issues that they may be responsible for the consequences of later, and many employees weigh heavily on the side of trying to bikeshed as much as possible.

The only advice I suggest is that you make it crystal clear, in the context of your organization, if possible, that these participants personal fate depends on their comprehension, contribution, and effort toward the real problem you are trying to solve. If that's the enterprise architecture, expressed in this -errant-codebase and all it failures, that's it. Make it clear to them that they must provide substantial meaningful input about that. Not some other randomness, that happens to be a pet-peeve of a senior somebody or other and will gain them nice brownie-points by agreeing with said senior somebody on.

This is often hard to do, as the senior somebody usually doesn't understand the technology going on, isn't interested, and unfortunately, controls the raw-ingredients: employee time; hire & fire, conference room politics, promotions, etc., etc. seriously, et cetera to the nth.


问:
Basic OOP theory: misunderstanding surrounding database and user classes
New to OOP and trying to understand some basic fundamentals. Currently using PHP5 to build a basic web app.

In using PHP's built in PDO as my database class and a separately created user class that handles, among other things, user log in and out, is it best to have the db class connect to the database in a log in situation, or does the user class need to directly connect to the db? If the latter, I think I'm likely misunderstanding how PDO would standalone.

If the former, presumably some kind of 'helper class' needs to be created that would facilitate the db connection between PDO and my user class?

答:
Basically you want only one connection to the db. The responsibility for connecting to and "talking" with the db should not be shared among many classes. You'll have to copy-paste host, username, password information, which will be quite bad, when you move your site around, and you have to hunt down all instances of connecting to the database and rewrite it. Pretty baaad.

So, my advice: login related functionality goes in Login class, DB related in DataBaseHandler class, formatting HTML in its own class, etc.

Example for DataBaseHandler:

DataBaseHandler.php:

```<code>class DataBaseHandler
{
     private $mysql_host = "myhost.example.com";
     ....

     function Connect()
     {
          $this->mysqli_object = mysqli_connect($this->mysql_host, $this->mysql_username, $this->mysql_password, $this->mysql_db);

          if ($this->mysqli_object->connect_errno)
          {
               print "Failed to connect to MySQL: " . $this->mysqli_object->connect_error;
          }
     }

     ....
}

$dbHandler = new DataBaseHandler;
$dbHandler->Connect();
</code>```

If you end up writing mySqlObject->connect(...) -s everywhere, you will be making a lot of work for yourself.

Update (regarding the comment)
The way I used it (probably not the best practice, since I had stopped writing php years ago) was I included the file of the class everywhere I needed. But you can ask around what's the best practice for that (static? global? composition???) in php. (In the simplest case in C# I would go for a lazy evaluated singleton, probably :))

Body:
Basically you want only one connection to the db. The responsibility for connecting to and "talking" with the db should not be shared among many classes. You'll have to copy-paste host, username, password information, which will be quite bad, when you move your site around, and you have to hunt down all instances of connecting to the database and rewrite it. Pretty baaad.

So, my advice: login related functionality goes in Login class, DB related in DataBaseHandler class, formatting HTML in its own class, etc.

Example for DataBaseHandler:

DataBaseHandler.php:

class DataBaseHandler
{
     private $mysql_host = "myhost.example.com";
     ....

     function Connect()
     {
          $this->mysqli_object = mysqli_connect($this->mysql_host, $this->mysql_username, $this->mysql_password, $this->mysql_db);

          if ($this->mysqli_object->connect_errno)
          {
               print "Failed to connect to MySQL: " . $this->mysqli_object->connect_error;
          }
     }

     ....
}

$dbHandler = new DataBaseHandler;
$dbHandler->Connect();

If you end up writing mySqlObject->connect(...) -s everywhere, you will be making a lot of work for yourself.

Update (regarding the comment)
The way I used it (probably not the best practice, since I had stopped writing php years ago) was I included the file of the class everywhere I needed. But you can ask around what's the best practice for that (static? global? composition???) in php. (In the simplest case in C# I would go for a lazy evaluated singleton, probably :))


问:
Can someone help me in creating a dynamic programming solution to this problem?
I have some function names which are assigned to some nodes. I have to decide which functions to move to other nodes to increase speed.

Why do I have to move the functions to other nodes? If communicating functions are on same nodes they take less time as compared to if communicating functions are on different nodes. A function might be communicating with several functions (all could be on different nodes). The question is which node do I move it to, to maximize the global performance.

I need to find a globally optimal solution using dynamic programming.

I have the following information

The integer value of the amount of data transferred between functions

The amount of time it takes to transfer data between nodes. Initially all functions have been assigned to some nodes.

Can somebody help me in mapping this problem to the assembly line scheduling algorithm (Dynamic programming) or creating some other dynamic programming solution to this problem?

The hard metric is the execution time of the entire program.The independent running time of a function is calculated by any timer API (We already have it).  Its (function's) actual running time would be equal to its independent running time + the running time of all the functions which are producing data consumed by this function + the communication time between this function and other functions on same node + the communication time between this function and functions on other nodes. The program's running time would then be the sum of the running time of all the functions in the program.

I have to minimize the execution time of the program which is the sum of the execution time of all the functions.Each functions execution time is the sum of its own time(precalculated) and the sum of all functions which will will execute before it and its sum with its time spent communicating with other functions(same or different nodes).

答:
So you have a scenario in which you have many variables which provide an easy-to-test result and you must absolutely know the optimal configuration?

Congratulations!  You have yourself an NP-Complete problem.  If you absolutely positively must know the optimal configuration, then you must perform a brute-force algorithm to try every single combination.  Really, we're not talking about a problem that much different than the bin packing problem.

However, that said, maybe you're flexible on finding that optimal solution.  Perhaps it doesn't have to be the best solution, but within 99% of the best solution.

Simulated annealing

Simulated annealing is an excellent approach in general, if you do not mind the fact that you will likely not get the optimal solution.  The biggest advantage to this approach is its speed, since you are essentially making better solutions out of existing good solutions.

Upsides:  Fast

Downsides:  Best solution is not likely

Genetic algorithm

Genetic algorithms are designed to specifically handle these types of problems, which is to say, many variables, but easy to test.  You'd have to define configuration solutions, be able to merge two configuration solutions, and be able to create a score based on that configuration (fitness).  From there, you generate a population of random configuration solutions and you run it until you get a solution which is satisfactory.

Upsides:  Far faster than brute force

Downsides:  Not very efficient if there are only a few nodes

Brute force

I would not automatically exclude the brute force algorithm just because it is the slowest.  If you have few nodes, you may find that you can get the optimal solution with minimum fuss.  In any case, it is the solution that would take the least amount of time to implement and it is worth trying if not to see if this is a feasible solution.

Upsides:  Easily implemented, guarantees optimal solution

Downsides:  Slow with large amounts of nodes

Conclusion

It's difficult to say what is best suited for your needs, however, one thing is for sure:  if getting the optimal solution is your priority, then it makes no difference which algorithm you apply for what concerns precision, since you must search the entire solution space to guarantee that you have the optimal solution.  For what concerns speed, brute force is going to be the fastest of the three, since the other algorithms are only ideal for finding a good solution efficiently.

Hope that helps!


答:
You have to decide what's more important in putting your code into public: Maintaining strict control or getting as many contributors as possible.

Personally, I think getting contributors is difficult. This person may not know the ramifications of using a different version of VS. There are plenty of hobbyists out there. Maybe you can ask if the person wouldn't mind converting back to 2010? They may have just downloaded the latest and greatests because that's what was most available.

It's like inviting someone into your house and telling them to make themselves at home and there's plenty of beer in the refrigerator. Obviously they should know to close the door when finished, but can you really expect them to recognize that they shouldn't use the broken handle you just glued?


问:
Problem regarding DRY principle and Polymorphism
I have a class that is 99% identical to its counter part. Sample code goes below:

```<code>public abstract class BaseClass
{
    void Method1() { }
    void Method2() { }
    void Method3() { }
    public void MainMethod(List<Object1> listObject)
    {
        Method1();
        Method2();
        Method3();
        Method4();
    }

    abstract internal void Method4();

}

public sealed class DerivedClass : BaseClass
{
    internal override void Method4()
    {
        throw new NotImplementedException();
    }
}

public class BaseClass2
{
    void Method1() { }
    void Method2() { }
    void Method3() { }
    public void MainMethod2(List<Object2> listObject)
    {
        Method1();
        Method2();
        Method3();
    }

}
</code>```

As You can see that BaseClass and BaseClass2 are almost identical with Method1 ... Method3.
Is there a better alternative that can be used to minimize duplication of code.

I initially started this polymorphism as an encouraging stuff, I have over 11 derived classes on BaseClass, and because of the second implementation of MainMethod2, I am stuck with duplication of code.

I just cannot think of any clever way to get out of it.

Update:
So this question is potentially containing two parts:

1. How to avoid duplication of code?
I solved this by using Composition successfully as suggested by wonderful answers below.

2. How to avoid leaky abstractions?
With this I am still struggling...

答:
I see two options.

Change BaseClass to contain an instance of BaseClass2. Change BaseClass.MainMethod to invoke BaseClass2.MainMethod (instead of its own implementation of Methods 1-3).

Refactor Method1, Method2, and Method3 into a new class. Change BaseClass and BaseClass2 to use the new class (instead of their own implementation of Methods 1-3).