答:
There is a deeper issue here: the fact that C# and Java insist most/all types must be distinguishable by name rather than structure: e.g. class MyPoint2D and class YourPoint2D are separate types even if they have the exact same definitions. When the type you want is "some anonymous thing with an x field and a y field" (i.e. a record), you're out of luck. So when you want to turn a YourPoint2D into a MyPoint2D, you have three options:

Write some tedious, repetitive, mundane boilerplate along the lines of this.x = that.x; this.y = that.y

Generate the code somehow.

Use reflection.

Choice 1 is easy enough in small doses but quickly becomes a chore when the number of types you need to map is large.

Choice 2 is less than desirable because now you have to add an extra step to your build process to generate the code, and make sure the entire team gets the memo. In the worst case you have to roll your own code generator or template system too.

That leaves you with reflection. You could do it yourself, or you could use AutoMapper.

Title: Am I wrong in thinking that needing something like AutoMapper is an indication of poor design?

Body:
Automapper is an "object-object mapper" for .Net, which means copying objects from a class into another class that represents the same thing.

Why is this ever useful? Is the duplication of classes ever useful/good design?


问:
Designing database related methods, which is better to return: true/false or row affected?
I have some methods that perform some data changing in a database (insert, update, and delete). The ORM I'm using return row-affected int values for those type of method. What should I return for "my method", in order to indicate the success/failure state of the operation?

Consider the code that is returning an int:

A.1

```<code>public int myLowerLevelMethod(int id) {
    ...
    int affectedRows = myOrm.deleteById(id)
    ...

    return affectedRows;
}
</code>```

Then usage:

A.2

```<code>public void myOtherMethod() {
    ...
    int affectedRows = myLowerLevelMethod(id)

    if(affectedRows > 0) {
        // Success
    } else {
        // Fail
    }
}
</code>```

Compare to using boolean:

B.1

```<code>public boolean myLowerLevelMethod(int id) {
    ...
    int affectedRows = myOrm.deleteById(id)
    ...

    return affectedRows > 0;
}
</code>```

Then usage:

B.2

```<code>public void myOtherMethod() {
    ...
    boolean isSuccess = myLowerLevelMethod(id)

    if(isSuccess) {
        // Success
    } else {
        // Fail
    }
}
</code>```

Which one (A or B) is better? Or pros/cons of each?

答:
The whole rows or an error status

Consider returning the whole rows, at least as a run-time option. In DB inserts you may need to inspect the data that was inserted - since it often will be different from what you sent to the DB; common examples include autogenerated row IDs (that the app will likely immediately need), default values determined by DB, and results of triggers if you use them.

On the other hand, if you don't need the returned data, then you also don't need the affected row count, since it's not helpful for the result of 0. If there are mistakes, then you need to return what kind of mistake happened, in a way consistent to your project error handling principles (exceptions, numeric error codes, whatever); but there are valid queries that will correctly affect 0 rows (i.e. "delete all expired orders" if there actually aren't any).

ContentLicense: CC BY-SA 3.0


问:
What is a helper? Is it a design pattern? Is it an algorithm?
Maybe a little tongue-in-cheek, but as I can't find this answer anywhere through Google, so to ensure Software Engineering has the answer:

What is a helper?

I have seen the name being used everywhere (module names, class names, method names), as if the semantics were deep and meaningful, but in the context of Computer Science (although I don't have a degree in it), I've never seen a description or definition anywhere!

Is it a design pattern? Is it an algorithm? I once worked on a program in which the module and class were both called somethingsomethinghelper (where somethingsomething was fairly generic too) and I promptly renamed it to something that made sense to me, but I feel like I'm missing something here!

答:
A helper is a harmless additional class or method, as long as it complements an external component. When it does the contrary, then it indicates bad design because the code has been excluded from its authority, if there is any authority at all.

Here is an example of a harmless helper, I use a method called FindRep that counts the number of leading zeros.

digits = digits.Remove(0, TextHelper.FindRep('0', digits, 0, digits.Length - 2));
```

<p>The helper method is very simple, but very inconvenient to copy-paste around and the framework does not provide any solution.</p>

<pre class="lang-cs prettyprint-override"><code>public static int FindRep(char chr, string str, int beginPos, int endPos)
{
    int pos;

    for (pos = beginPos; pos <= endPos; pos++)
    {
        if (str[pos] != chr)
        {
            break;
        }
    }

    return pos - beginPos;
}
</code>```

And here is an example of a bad helper:

public static class DutchZipcodeHelper
{
    public static bool Validate(string s)
    {
        return Regex.IsMatch(s, @"^[1-9][0-9]{3}[A-Z]{2}$", RegexOptions.IgnoreCase);
    }
}

public class DutchZipcode
{
    private string value;

    public DutchZipcode(string value)
    {
        if (!DutchZipcodeHelper.Validate(value))
        {
            throw new ArgumentException();
        }

        this.value = value;
    }

    public string Value
    {
        get { return value; }
    }
}
```

Body:
A helper is a harmless additional class or method, as long as it complements an external component. When it does the contrary, then it indicates bad design because the code has been excluded from its authority, if there is any authority at all.

Here is an example of a harmless helper, I use a method called FindRep that counts the number of leading zeros.

digits = digits.Remove(0, TextHelper.FindRep('0', digits, 0, digits.Length - 2));

The helper method is very simple, but very inconvenient to copy-paste around and the framework does not provide any solution.

public static int FindRep(char chr, string str, int beginPos, int endPos)
{
    int pos;

    for (pos = beginPos; pos <= endPos; pos++)
    {
        if (str[pos] != chr)
        {
            break;
        }
    }

    return pos - beginPos;
}

And here is an example of a bad helper:

public static class DutchZipcodeHelper
{
    public static bool Validate(string s)
    {
        return Regex.IsMatch(s, @"^[1-9][0-9]{3}[A-Z]{2}$", RegexOptions.IgnoreCase);
    }
}

public class DutchZipcode
{
    private string value;

    public DutchZipcode(string value)
    {
        if (!DutchZipcodeHelper.Validate(value))
        {
            throw new ArgumentException();
        }

        this.value = value;
    }

    public string Value
    {
        get { return value; }
    }
}


问:
Value of passing by reference
In C++, we have the option to pass by reference or pass by value.

The client code does not need to know which one a parent function uses; that is, int func(int param) and int func(int &param) are called in exactly the same manner from the client code. Isn't this dangerous?

If I'm writing code on the client side, I don't know which of the variables I pass to a function might be changed and which I can expect to remain the same without an explicit knowledge of the parent function declaration. What is the advantage of doing it this way versus explicitly expecting a pointer (e.g., int func(int *param), which would then be called func(&param);)?

When you have to have a pointer, it's easy enough for the client to know which values may be modified - the ones that have an & in front. Alternatively, why not have everything be pass-by-reference, so that there is no guess-work of "Can this function change this value?" The answer is universally yes.

答:
The differences between references and pointers have been extensively discussed, sometimes even here. That discussion probably shouldn't be re-started.

But the other question - "Why not have everything as X or Y?" is easily answered. C++ gives you both options as a matter of principle, because you might want to use X, but you also might want to use Y.

In such cases the language virtually always offers both on the principle that if one of the two allows a solution that is even slightly better, more effective etc., then the language must contain both. Recall that you can even write your own class-specific memory allocators and deallocators. The language designers are firmly of the opinion that at least some of their users will be able to build a better special-purpose allocator than they could build into the compiler, so they mustn't do anything that prevents this. This is part of the reason why C++
has such an extraordinarily rich set of interacting features, even when they are only slightly different.

Title: Value of passing by reference


问:
subclass reference to another subclass
Imagine I have the following code:

```<code>class A:
    pass

class B(A):
    pass

class C(A):
    def __init__(self):
        self.b = B()
</code>```

Is the above code correct in terms of correct inheritance? I mean is it a good practice to reference another subclass in a subclass?

答:
Bags and suitcases are both types of containers. You can also put bags inside suitcases, and vice versa. Containment doesn't care about inheritance, and inheritance doesn't care about containment.

The two concepts are entirely orthogonal, and as such there is no 'best practice' here.

Title: subclass reference to another subclass


答:
It depends. In some languages (like Java), you don't really have a choice because every class (except Object) is a subclass.

If class C needs some functionality from class B to do its work, but you can't describe instances of class C as also being instances of class B (C can't work as a drop-in replacement for B), then your design is absolutely correct.

Title: subclass reference to another subclass

Body:
Imagine I have the following code:

```<code>class A:
    pass

class B(A):
    pass

class C(A):
    def __init__(self):
        self.b = B()
</code>```

Is the above code correct in terms of correct inheritance? I mean is it a good practice to reference another subclass in a subclass?


问:
How to deal with a new version of visual studio's directory?
When upgrading Visual Studio to a newer version, a new directory is created e.g. "Visual Studio 2013". I understand that that makes sense as we want to differentiate between code targeting different versions of .net. But since some projects use other projects as their dll's for some repeated code - this raises a question - should we copy everything and have everything separate for .net 4.0 from .net 4.5 or should we have one library that works for both (since 90% of the code will be the same) and only create a special library for code that can't run on 4.0?

Just suggesting doing "whatever works for you" is not a good solution - at the moment both look viable. If one of the options has some disadvantages, they might become apparent only after we have many internal links from solution to solution, and there's no real way to change all links at once - one must search for every one of them manually, hoping not to miss anything.

Since we're obviously not the first facing this question, I'd like to hear from those with experience in the matter. (or anyone else, of course.)

(Though there might not be a clear cut answer to this question, I hope it will be allowed here just as the highest voted question on this site is.)

答:
The proper answer in 2014 is none of the above. First, that default file save location has no real meaning in life -- I suspect it is just Microsoft following their own rules about where programs should save things by default.

As for how to deal with cross-cutting dependency projects, the right answer is to treat them as projects in their own right with their own source control and build systems and leverage nuget to use them in other projects. If you can't hack that I would suggest letting each project keep a copy of the dependent DLLS (and sources if possible) so they stand on their heads.

Directly referencing build output like you seem to be doing creates some versioning nightmares to say the least. If that is your only option I would strongly consider just statically including the code in the project that is using it so it has it's own "library."


问:
Why don't I see many unit test projects that bring up and tear down a DB? (ASP.NET MVC)
I see all the examples that demonstrate unit testing code and mocking the calls to the DB since you are not suppose to touch the DB. But it seems to me having a set up tasks that uses the actually schema, loads the lookup tables and then populates it with data using the methods to be tested... This way it is more real world testing and all the stored procedures are tested as well.. But I never have seen any examples like this...  Is there some reason I do not understand why using this technique is not as useful as it seems ? </p>

<p>EDIT1: Sorry.. I shouldn't have called it unit test.. yes. I will have unit tests as well that are for testing code.. But beyond that it seems like a good idea to bring up and tear down and DB and have code that modifies that DB and does assertions.. But I don't want this to be UI testing.. I just want to perform a lot of CRUD functions and a lot of assertions .. :My question is #1 does this make sense.. #2 how do I automate this all within visual studio ? How do I tell VS 2012 to run a SQL script before running the tests? is there some special API for this ? </p>

答:
This is not horribly straightforward but not impossible. The biggest hurdle is picking a tool and method to automatically stand up the database in the state you want that will work silently from the command line. Personally I prefer roundhouse for this task but there are certainly other options. Insofar as getting it integrated with visual studio, the most straightforward way is to create a custom configuration and hack the call to the executable to build the database into the custom build settings.

The next question is "what kind of database to build and how to test against it?"

The approach that I think makes the most sense is to deploy an empty copy of the schema and then have each test responsible for creating the test data it needs and well as cleaning up after itself. This will take a bit longer per test to run through but it keeps you out of cross-cutting concerns between tests.

Finally, as others have indicated this is going to be slow so if you could separate this out into it's own project that could be worth it.


问:
How bad is using underscore in names?
I am mainly a C programmer. In my world, writing likeThis or like_this is just a matter of style. In Haskell however, it seems that camelCase is the definite choice. Personally, I find the later much more readable. Think pthread_mutexattr_init vs PthreadMutexAttrInit.

What's more, I have configured vim to swap the numbers and their alternate symbols (in C), since numbers happen to be written much less frequently than symbols such as parentheses, star, ampersand etc, which makes life easier on my wrist. As a bonus, this lets me write this_sort_of_thing without using the shift key.

My question is, from the Haskell programmers, whether using underscore in names is acceptable to the Haskell community or not. Is camelCase an unwritten rule or common convention? Would it be ok to make the public functions likeThis but internally write like_this?

答:
We conform to conventions and standards so that our code is intuitive for other programmers to work with.

```<code>private string _field;

public string Property { get; set; }

public void PublicMethod(string parameter)
{
    string localVariable;
}

private void privateMethod()
{

}
</code>```

Most people that have been in a microsoft shop for a few years would be pretty familiar with this convention.

I wouldn't need to question the scope of _appleCore or AppleCore; I know _appleCore is a private field and AppleCore is a public property.

Part of your pride as a developer should be in how easily other people can understand and work with your code. Making maintainable and extensible code means making it maintainable/extensible for other people as well, not just ourselves.

As for the question about Haskall specifically:
http://www.haskell.org/haskellwiki/Programming_guidelines#Naming_Conventions

They have guidelines, but ultimately the owner of the codebase can define the convention as whatever they choose, that much isn't open for debate or question. Thus, this question you ask can't be answered definitely by us.

Title: How bad is using underscore in names?

Body:
We conform to conventions and standards so that our code is intuitive for other programmers to work with.

private string _field;

public string Property { get; set; }

public void PublicMethod(string parameter)
{
    string localVariable;
}

private void privateMethod()
{

}

Most people that have been in a microsoft shop for a few years would be pretty familiar with this convention.

I wouldn't need to question the scope of _appleCore or AppleCore; I know _appleCore is a private field and AppleCore is a public property.

Part of your pride as a developer should be in how easily other people can understand and work with your code. Making maintainable and extensible code means making it maintainable/extensible for other people as well, not just ourselves.

As for the question about Haskall specifically:
http://www.haskell.org/haskellwiki/Programming_guidelines#Naming_Conventions

They have guidelines, but ultimately the owner of the codebase can define the convention as whatever they choose, that much isn't open for debate or question. Thus, this question you ask can't be answered definitely by us.


问:
Developing pages in MVC website that will be specifically used as an iframe by another website
I have a website where I'm going to be partnering with another website. They want to view one specific page of mine, in their [WordPress] website. They aren't developers, so I looked into how to do this.

At first glance, it appears as though the WordPress iFrame plugin is the easiest route. My next thought is, they'll probably still want to show their own header and footer in their page, while showing the content of my page in the iFrame. No big deal.

I'm thinking of developing a View on my [MVC 4] website that will be used ONLY for their iFrame purposes. Since they'll probably want their own headers, I'll probably design a page that uses no layout, and just a custom header and/or footer that shows that the information is coming from MY website.

Here are my questions:
1) The page that will be displayed contains MANY anchor tags, if that's embedded in an iFrame, what happens if the user on THEIR website clicks the link in the iFrame? Does the iFrame page change, or does their ENTIRE page change?

2) Depending on the answer to #1, should I just disable all hyperlinks/anchor tags in the iFrame page on my site so it doesn't cause any funkyness on their site?

3) What if I WANT some hyperlinks on the iFrame page so they come visit my website? Is that a matter of telling them to put a real link on their site to my own?

4) What security concerns do I have with allowing a page of my own to be accessible via iFrame from another site? Should I only allow traffic to my iFrame page when it's from their site? If it's not from their site, then re-direct to my "real" page?

Thanks all!

答:
1) The page that will be displayed contains MANY anchor tags, if that's embedded in an iFrame, what happens if the user on THEIR website clicks the link in the iFrame? Does the iFrame page change, or does their ENTIRE page change?

Iframes are self-contained websites. As such, any links inside the iframe will change only the contents of the iframe, unless the link has specified the target attribute.

A good example of this in practice are Facebook tab apps. Many Facebook tab apps are actually iframes of external sites built for use into the Facebook iframe.

2) Depending on the answer to #1, should I just disable all hyperlinks/anchor tags in the iFrame page on my site so it doesn't cause any funkyness on their site?

It might be an option, if those links will go to somewhere that has your branding on it. Otherwise, it's not necessary.

3) What if I WANT some hyperlinks on the iFrame page so they come visit my website? Is that a matter of telling them to put a real link on their site to my own?

Them linking to your own is one way, another is to use the target attribute. To open the link in a new window/tab (so the user can still easily get back to the page with the iframe in it), you'd use target=_blank. To open the link in the same tab/window, requiring the user to hit the "back" button to get back to the page with the iframe in it, you'd use target=_top.

For more information on anchor (link) attributes, and more detailed descriptions of the values available for target, see the MDN article on anchors.

4) What security concerns do I have with allowing a page of my own to be accessible via iFrame from another site? Should I only allow traffic to my iFrame page when it's from their site? If it's not from their site, then re-direct to my "real" page?

Since iframe content is self-contained, and is basically just a stand-alone page being accessed from inside another one, you have the same security concerns as you would for any other page of the same nature as the iframe content. The container page cannot access the contents of the iframe, and the iframe cannot access the container page. Therefore, visiting the page outside of the context of the iframe does not pose any security risks that aren't also present when visiting from inside the iframe. (Note - there are ways that you can open communication channels via JavaScript and/or server-side code, between the iframe container and the content, but that requires code on both sides and intentionally opening up such channels. See again, Facebook tab apps.)

Now, there is the matter of user experience, when it comes to the chance of a user visiting the page outside of the iframe. The chance of someone seeing it outside of the iframe context can be minimized by taking measures to exclude it from spider crawling (so it doesn't show up in search engines), and to not link to it outside of the iframe context. If you really want, you can use JavaScript to see if the iframe content's loading context is the top to determine if it's in an iframe, and redirect the user as necessary, though it should be noted that turning off JavaScript will defeat that, so it's not bulletproof.


问:
Testing Facades, Is it a good idea?
I stumbled across a need to create a thin I/O Layer interface to abstract away a class from the need to know about I/O

```<code>public interface IFileIOProvider {
    Task WriteFileAsync(String contents, String path);
    Task<String> ReadFileAsync(String path);
}
</code>```

Is it a good idea to test a default implementation that only falls back to standard .Net System.IO classes, no logic attached?. I think it might be overkill, but just want to get my strategy checked out by more experienced programmers

答:
First of all this should be tested by system/acceptance tests that cover what ever feature needs this class

for unit tests I'd say the answer is mostly no, there is nothing useful to test here, the only time I would unit test is if it was more effort to justify why I'm not testing this class than to test it (sometimes the case with safety related stuff)

Title: Testing Facades, Is it a good idea?


答:
If I'm writing code on the client side, I don't know which of the variables I pass to a function might be changed and which I can expect to remain the same without an explicit knowledge of the parent function declaration.

This is as it should be. When you call an API, you should know what you are calling and why. You should also know what the function does and what it's side effects are (and preconditions and postconditions as well).

What is the advantage of doing it this way versus explicitly expecting a pointer (e.g., int func(int *param), which would then be called func(&param);)?

I will assume that "doing it this way" means "passing by reference".

It seems to me you make the association "received by pointer = may be changed". This is incorrect.

Here are two scenarios when passing by reference/pointer is prefered over the alternative:

operators:

```<code>class EvenInteger { int value; public: /*...*/ }; // 0, 2, 4, 6, ...

EvenInteger operator +(const EvenInteger& x, const EvenInteger&y);
</code>```

Here, passing by reference would disble the operator for temporary values, passing by pointer would result in client code like this:

```<code>EvenInteger a{0}, b{122};
auto c = &a + &b; // addition by address imposed if operator received pointers
</code>```

instance observer (naturally pass 'this' as an argument):

```<code>class Collection // collection/sequence of arbitrary objects of type Obj
{
public:
    class InterestingIterator {
        Collection* parent;
        InterestingIterator(Collection* c); // accessible by Collection
    public:
        // ...
    }

    InterestingIterator begin() { return InterestingIterator{this}; }
};
</code>```

The implementation of begin, naturally receives a this pointer, without implying it is in any way a return value. Writing the iterator to receive a reference imposes the *this construct on client code.

As a rule, the interface of an API should tell you this:

```<code>void f(int x); // makes own copy of x, doesn't return/alter value
void f(int& x); // _may_ alter value (check docs)
void f(int* x); // _may_ alter value, or populate it with a return (check docs)
void f(const int& x); // observer of x
void f(int* const x); // _may_ alter value pointed by x, but not the address
void f(const int* x); // _may_ alter address, but not the pointed value
void f(const int* const x); // observer of value and address
</code>```

As you can see, you should (always) rely on an API's documentation. If you rely on a function signature, it can only tell you when it doesn't alter it's received parameters, and you see that through const, not through the parameter type (address/reference/etc).

This also implies that you should always write documentation for your APIs.

Title: Value of passing by reference

Body:
In C++, we have the option to pass by reference or pass by value.

The client code does not need to know which one a parent function uses; that is, int func(int param) and int func(int &param) are called in exactly the same manner from the client code. Isn't this dangerous?

If I'm writing code on the client side, I don't know which of the variables I pass to a function might be changed and which I can expect to remain the same without an explicit knowledge of the parent function declaration. What is the advantage of doing it this way versus explicitly expecting a pointer (e.g., int func(int *param), which would then be called func(&param);)?

When you have to have a pointer, it's easy enough for the client to know which values may be modified - the ones that have an & in front. Alternatively, why not have everything be pass-by-reference, so that there is no guess-work of "Can this function change this value?" The answer is universally yes.

Body:
If I'm writing code on the client side, I don't know which of the variables I pass to a function might be changed and which I can expect to remain the same without an explicit knowledge of the parent function declaration.

This is as it should be. When you call an API, you should know what you are calling and why. You should also know what the function does and what it's side effects are (and preconditions and postconditions as well).

What is the advantage of doing it this way versus explicitly expecting a pointer (e.g., int func(int *param), which would then be called func(&param);)?

I will assume that "doing it this way" means "passing by reference".

It seems to me you make the association "received by pointer = may be changed". This is incorrect.

Here are two scenarios when passing by reference/pointer is prefered over the alternative:

operators:

class EvenInteger { int value; public: /*...*/ }; // 0, 2, 4, 6, ...

EvenInteger operator +(const EvenInteger& x, const EvenInteger&y);

Here, passing by reference would disble the operator for temporary values, passing by pointer would result in client code like this:

EvenInteger a{0}, b{122};
auto c = &a + &b; // addition by address imposed if operator received pointers

instance observer (naturally pass 'this' as an argument):

class Collection // collection/sequence of arbitrary objects of type Obj
{
public:
    class InterestingIterator {
        Collection* parent;
        InterestingIterator(Collection* c); // accessible by Collection
    public:
        // ...
    }

    InterestingIterator begin() { return InterestingIterator{this}; }
};

The implementation of begin, naturally receives a this pointer, without implying it is in any way a return value. Writing the iterator to receive a reference imposes the *this construct on client code.

As a rule, the interface of an API should tell you this:

void f(int x); // makes own copy of x, doesn't return/alter value
void f(int& x); // _may_ alter value (check docs)
void f(int* x); // _may_ alter value, or populate it with a return (check docs)
void f(const int& x); // observer of x
void f(int* const x); // _may_ alter value pointed by x, but not the address
void f(const int* x); // _may_ alter address, but not the pointed value
void f(const int* const x); // observer of value and address

As you can see, you should (always) rely on an API's documentation. If you rely on a function signature, it can only tell you when it doesn't alter it's received parameters, and you see that through const, not through the parameter type (address/reference/etc).

This also implies that you should always write documentation for your APIs.


问:
Program Design clearness vs convenience
I've recently disputed with my colleague about the following situation:

I've developed a framework that processes the resources (in java, although its not really important). It goes (simplified, pseudo-code) like this:

```<code>class Algorithm {
    Processor processor = ...;
    execute() {
        forEach(Resource r : readResourceNamesFromFileSystem()) {
           DomainObject do = convertResourceToDomainObject(r);
           processor.process(do);
        }
    }

}

interface Processor {
     process(DomainObject do);
}
</code>```

Class Algorithm is an entry point to my framework. Resource is a representation of some content in the filesystem (it has methods for reading the data from file and the file name, which is important)

Class DomainObject (declaration is omitted) is a java representation of the content of the file depicted by Resource. DomainObject only has data and doesn't have a filename inside.

Class Processor represents the business logic layer, the DomainObject can be processed, stored in Database and so forth.

The content data is supplied by others, we just know that these files contain the data that can be converted into DomainObject(s) which is a real object we work with in the framework. We store one DomainObject in one file.

Now we argue about the file name. Colleague of mine wants the file name to be propagated into the Processor and potentially to all the layers because  its easy to print the logging message/throw an exception that contains a file name if something goes wrong during the processing, or maybe to write the message like "domain object stored in file (here__comes__filename) has been processed successfully".

I see the point of my colleague (convenience) but I'm sure it breaks the design and encapsulation because the processor module shouldn't really be aware of the "origin" of the DomainObject (today we store them in files one DomainObject per file, tomorrow we'll maybe use something else, something that doesn't necessarily has a filename).

I claim that we better catch the exception in the Algorithm.execute method and rethrow the exception with a filename/ log the filename. The log file will be less readable but the encapsulation won't be broken.

In my understanding its a design vs clearness. Could you please share your opinion, who is right, who is wrong? Should I sacrifice the design for the clearness of logs?

BTW I've promised my colleague to ask this question so we'll read the possible answers together :)

Thanks a lot in advance and have a nice day

答:
If you're using a logging framework like Log4j, you can use a nested diagnostic context (NDC) to store the file name at the point it is available, then retrieve from the NDC at the time you log the messages.

Logj4 NDC

This can be even more useful because you can actually write a log4j appender that handles log messages specially based on the NDC content.

The specific case I used this was an embedded Jetty web server. Parts of the incoming URI identified the customer e.g.

```<code>http://domain/app/<customer-name>/otherstuff...
</code>```

The Jetty request dispatcher extracted the value of "customer-name" from the URI and stored it in the Log4j NDC.

It was almost trivial to write a log4j appender that, when the NDC contained a customer name value, appended the message to a .log file.

That way we had a single coherent log file that contained all the diagnostic information in sequence, plus we had logs of activity relevant (and private) to each customer.

Title: Program Design clearness vs convenience

Body:
If you're using a logging framework like Log4j, you can use a nested diagnostic context (NDC) to store the file name at the point it is available, then retrieve from the NDC at the time you log the messages.

Logj4 NDC

This can be even more useful because you can actually write a log4j appender that handles log messages specially based on the NDC content.

The specific case I used this was an embedded Jetty web server. Parts of the incoming URI identified the customer e.g.

http://domain/app/<customer-name>/otherstuff...

The Jetty request dispatcher extracted the value of "customer-name" from the URI and stored it in the Log4j NDC.

It was almost trivial to write a log4j appender that, when the NDC contained a customer name value, appended the message to a .log file.

That way we had a single coherent log file that contained all the diagnostic information in sequence, plus we had logs of activity relevant (and private) to each customer.


问:
How can I close my Open Source project and what is required from me in order to make it closed source?
Let's say I wanted to close my "GPL v 2.0 (or similar)" licensed project, to which I'm the only contributor, and make it closed source.

Do I still need to make the existing "GPL v 2.0 (or similar)" licensed code available after closing the project or can I refuse giving out the source code for old revisions that was previously "GPL v 2.0 (or similar)" licensed?

Can I theoretically keep the the code "GPL v 2.0 (or similar)" licensed even after removing the public source code or do I have to distribute the source code if I'm using a "GPL v 2.0 (or similar)" license?

答:
There is a good, long, accepted answer already. This is a short answer.

Yes, as the sole copyright owner you can change the licence for all future distributions. You cannot change history.

Yes, if you have ever distributed binaries without source code under GPL then the obligation to provide source code of that version to those who relied on it is permanent. It never goes away.

What happens in the future depends absolutely on what licence you choose for any future distributions and (for you alone) is not affected by what you did in the past.


答:
A library which is created for .NET Fw 4.0 (or before, down to 2.0) should be (in most real-world cases) usable from any 4.5 project (the opposite is not true). So as long as there is no compelling reason to upgrade a library to .NET Fw 4.5, I would recommend to stay at 4.0, at least as long as you have at least one project which is 4.5 based which uses that lib. That strategy will allow you to have one library which works for both kind of projects, without the need for duplicating anything.

Note that you will not have to install an older VS version for maintaining the 4.0 lib - VS 2013 supports 4.0 as well as 4.5 projects, and it even does not enforce an version upgrade for projects files of older VS versions.

If you cannot avoid the need to keep a 4.0 version of a library under maintenance in parallel to a 4.5 version of the same lib, try to keep the changes to the 4.0 small, use an appropriate branching model of your version control system, and make sure you can transparently bugfix the 4.0 version while implement new features into the 4.5 version in parallel. But be aware that every bugfix for the 4.0 version will have to be merged into the 4.5 version as well, so you may generate some additional effort this way.

Title: How to deal with a new version of visual studio's directory?

Body:
When upgrading Visual Studio to a newer version, a new directory is created e.g. "Visual Studio 2013". I understand that that makes sense as we want to differentiate between code targeting different versions of .net. But since some projects use other projects as their dll's for some repeated code - this raises a question - should we copy everything and have everything separate for .net 4.0 from .net 4.5 or should we have one library that works for both (since 90% of the code will be the same) and only create a special library for code that can't run on 4.0?

Just suggesting doing "whatever works for you" is not a good solution - at the moment both look viable. If one of the options has some disadvantages, they might become apparent only after we have many internal links from solution to solution, and there's no real way to change all links at once - one must search for every one of them manually, hoping not to miss anything.

Since we're obviously not the first facing this question, I'd like to hear from those with experience in the matter. (or anyone else, of course.)

(Though there might not be a clear cut answer to this question, I hope it will be allowed here just as the highest voted question on this site is.)


问:
Is this a good practice or not?
I have a colleague who has come up with a way of 'genericizing' information from a database so that all his web application's drop-down lists can share the same object in his MVC.NET C# code and Views, which can contain different data depending on what tables it is being used against.

We work for a government agency, and we have facilities divided up into areas called "Regions", which contain further subdivided areas called VISNs, which each contain "Sites" or "Facilities". My colleague has developed a very complex security scheme whereby people can be granted access to data based on their permission level which can be assigned by Region, VISN, Site, or any mixture of the three. It's a nice scheme and very clever. However, he has stored procedures that return lists of Regions, VISNs, and Sites based on a person's User Id, and he is returning "generic" values like TextFieldID, TextField, and TextParentID. My first problem with this, is that looking at this data coming out of the database, I would not know what the data is. I feel that fields coming from a query or stored procedure should be descriptive of the data they are delivering. What does everyone else think? The deeper issue for me however is that he is taking some of the data, concatenating it in his stored procedure like this

SELECT DISTINCT
    t.VisnID,
    NULL,
    t.StationID,
    'V' + CAST(t.VisnID as varchar) + ': ' + t.Station3N + ': ' + t.StationName,
    t.Inactive
FROM Stations t
```

<p>and sending it back in a "TextField" property, instead of sending back the discrete data separately (<code>Station3N</code>, <code>StationName</code>) and concatenating it in the View, which would allow for different concatenation depending on what device what accessing the application (perhaps mobile and desktop). His justification is that he can send all his various drop down data and capture them all, regardless of content, in the same C# object named "LookupValue." </p>

```public partial class LookupValue : IEquatable<LookupValue>
{
    public LookupValue(string textFieldId, string textField, bool inactive)
    {
        TextFieldID = textFieldId;
        TextField = textField;
        Inactive = inactive;
    }

    public LookupValue(string textParentId, string textFieldId, string textField, bool inactive)
    {
        TextParentID = textParentId;
        TextFieldID = textFieldId;
        TextField = textField;
        Inactive = inactive;
    }

    public LookupValue(string textParentId, string textSelfParentId, string textFieldId, string textField, bool inactive)
    {
        TextParentID = textParentId;
        TextSelfParentID = textSelfParentId;
        TextFieldID = textFieldId;
        TextField = textField;
        Inactive = inactive;
    }

    ///
    /// Returns a custom string identifier if the Inactive property is true.
    ///
    public string GetInactiveString()
    {
        string value = "";
        if (Inactive)
        {
            value = "[I]";
        }

        return value;
    }

    ///
    /// Returns a custom text label that concatenates the TextField property with the custom string identifier of the Inactive property.
    ///
    public string GetDisplayNameWithInactiveString
    {
        get { return TextField + " " + GetInactiveString(); }
    }

    public bool Equals(LookupValue other)
    {
        //Check whether the compared object is null.
        if (Object.ReferenceEquals(other, null)) return false;

        //Check whether the compared object references the same data.
        if (Object.ReferenceEquals(this, other)) return true;

        //Check whether the products' properties are equal.
        return TextFieldID.Equals(other.TextFieldID) && TextField.Equals(other.TextField);
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.
    public override int GetHashCode()
    {
        //Get hash code for the TextFieldID field if it is not null.
        int hashTextFieldId = TextFieldID == null ? 0 : TextFieldID.GetHashCode();

        //Get hash code for the Code field.
        int hashTextField = TextField.GetHashCode();

        //Calculate the hash code for the product.
        return hashTextFieldId ^ hashTextField;
    }
}
```

He believes the re-usability of this object is worth the violation of Separation of Concerns and possible future difficulties in handling more than one display variation for a drop-down. I should point out that this object is contained in his Data project namespace (our projects are separated into Data, Web, Services, etc.) instead of the Web project namespace and he also returns this object to the Web layer via his Repository queries which call the stored procedures that I described earlier,  which is gross violation of Separation of Concerns in my opinion.

I am just looking for some confirmation from other programmers that this is in fact a bad practice, and also looking for ideas I can present him on better ways to do what he is attempting. I have my own ideas, but again I'm just looking for other's ideas so I have more options to present to him.

--Edit -- I forgot to mention that we are using Entity Framework as an ORM, and his Repository classes in his DAL are dumping the data from the stored procs into this LookupValue object.

答:
This sounds suspiciously like an inner platform.

Here are the potential problems:

You'll be writing queries that query the database for what information to query (metaqueries) first, rather than queries that simply retrieve the needed information.

You'll be subverting the role of the database, which already provides metadata capabilities such as rows, columns, and meaningful field names and data types.

You'll be defeating the indexing and querying capabilities of the database (JOINs, etc).

There's magic strings everywhere.

For an extreme example of where this can lead, read Can a system be 100% Data Driven?

There are better ways to accomplish what your fellow programmer desires, while still preserving an orthodox database and application design.  Check out Automapper for an alternative.

Title: Is this a good practice or not?


问:
Beginning Design as a Programmer
I'm just starting to get in to web development. I'm learning Rails at the moment. I have lots of experience with various programming languages.

I've been searching for books to help me get started; I want to focus on writing clean, standards-compliant HTML and CSS.

Does anyone know of any modern, standards-based resources I can use, particularly books?

Thanks!

答:
I've found that trying to duplicate existing site designs is a great way to learn graphics and CSS techniques.

For instance, sites like http://microsoft.com and http://www.mozilla.com/en-US/ are built around software products, but both do things a little differently.  Understanding what is going on here, as well as the audience they are trying to reach will help you as well.

Find a site you like and see how well you can duplicate it.

Also, for CSS practice http://csszengarden.com is nice and follows the advice above.

ContentLicense: CC BY-SA 2.5

Title: Beginning Design as a Programmer


问:
Coupling business logic with class definitions
Perhaps it is my scripting background, but my perspective is that the purpose of an object should be to contain data. Classes are necessary in that they provide templates and standard ways to classify and construct objects with particular data attributes. Standard protocol in object oriented design seems to be to include business logic in class definitions.

In a system that depends on state, I understand the motivation behind binding methods with the sole purpose of altering or retrieving the state of an object to the class definition. So let's exclude simple getters, setters, and constructors from the scope of the conversation.

The problems, as I see them, start when processes are bound to an object.

Consider a simple "string.equals()" method that accepts a string as a parameter, and returns a boolean indicating whether strings are equivalent. I think this simple method can cause enormous problems.

Let's say I have a LocationString class that inherited from String, where equals() is overridden as follows:

```<code>Boolean equals(LocationString otherLocation) {
    return extractCountry().equals(otherLocation.extractCountry());
}

String extractCountry(){
    return this.getCountry();
}
</code>```

Now, assume I have a thousand such different objects with different equals() definitions, some of which are the same, and some of which are vastly different. Suddenly, the definition of equality changes for some of my classes. It becomes extremely painful to work out which equals definitions need to be changed. It becomes painful to work out whether other internal processes which called the equals method need to be changed. And eventually as the system expands, more hours are wasted searching through the code than analyzing it.

As such, to me it makes far more sense that a generic equals rule is defined that modifies its behavior polymorphically depending on the inputs it receives. Consider the following definition:

```<code>public static Boolean equals(Object a, Object b) {
    List locationClasses = Arrays.asList("LocationString")
    if (locationClasses.contains(a.getClass().getName()) && locationClasses.contains(b.getClass().getName()){
        return equals(a.extractCountry(), b.extractCountry());
    }
    else {
        return StringUtils.equals(a,b);
    }
}
</code>```

If all processes were defined externally, a change in process would not be all that difficult to correct and provided these more generic rules could be stored and categorized logically, they would be easy to find and would only need to change once as the business logic changes.

This approach seems relatively simple and straight forward. Why then, has it been generally rejected in favor of the typical object oriented coupling of data with methods?

答:
I understand that the case of equals is just an example and that your approach is about any logic besides simple getters and setters.

I see some serious problems/limitations with what you propose:

That "general equals" method should reside in an utility class.

That class would need to be changed every time a class is added to the system ( if you will ever need to compare them )

Many APIs need you to overwrite equals in order for generic collections to work with your classes in sort operations. No way an APIs will look at the utility class's equals method to compare objects.

Not unlike the API example I gave above, plugin architectures, which allow for escalability and extensibility, would not exist as we know it. Explanation: Were your approach used in the development of, say, Firefox, then a plugin would only work if its existence were known to Firefox's developers and they added the corresponding case. Since that approach was not used, a plugin can work even when the developer of Firefox didin't know anything about such a plugin's existence. Even plugins developed after a given Firefox version was released, would work with it.

Also you seem to imply that every logic inside a method is "business logic". That's not the canonical definition of business logic.


答:
There are two points to say about this.

In some cases thinking about processes as belonging to objects makes understanding the system indeed easier. The objects become responsible for their own processes.

Unfortunately most object-oriented programming languages do not support multi-methods, i.e. the dispatch is only dynamic in regard to one parameter (this).

But, of course, an object oriented approach is not always suitable for all kinds of systems. Personally, I think, it mostly pays off for transactional systems with very complicated business rules. The business logic can then be distributed across multiple classes and, assuming that the system is well designed, even if you don't understand the whole system at once, it is still possible to maintain it by working with limited number of classes (each encapsulating specific behavior) at a time.

Title: Coupling business logic with class definitions

Body:
Perhaps it is my scripting background, but my perspective is that the purpose of an object should be to contain data. Classes are necessary in that they provide templates and standard ways to classify and construct objects with particular data attributes. Standard protocol in object oriented design seems to be to include business logic in class definitions.

In a system that depends on state, I understand the motivation behind binding methods with the sole purpose of altering or retrieving the state of an object to the class definition. So let's exclude simple getters, setters, and constructors from the scope of the conversation.

The problems, as I see them, start when processes are bound to an object.

Consider a simple "string.equals()" method that accepts a string as a parameter, and returns a boolean indicating whether strings are equivalent. I think this simple method can cause enormous problems.

Let's say I have a LocationString class that inherited from String, where equals() is overridden as follows:

```<code>Boolean equals(LocationString otherLocation) {
    return extractCountry().equals(otherLocation.extractCountry());
}

String extractCountry(){
    return this.getCountry();
}
</code>```

Now, assume I have a thousand such different objects with different equals() definitions, some of which are the same, and some of which are vastly different. Suddenly, the definition of equality changes for some of my classes. It becomes extremely painful to work out which equals definitions need to be changed. It becomes painful to work out whether other internal processes which called the equals method need to be changed. And eventually as the system expands, more hours are wasted searching through the code than analyzing it.

As such, to me it makes far more sense that a generic equals rule is defined that modifies its behavior polymorphically depending on the inputs it receives. Consider the following definition:

```<code>public static Boolean equals(Object a, Object b) {
    List locationClasses = Arrays.asList("LocationString")
    if (locationClasses.contains(a.getClass().getName()) && locationClasses.contains(b.getClass().getName()){
        return equals(a.extractCountry(), b.extractCountry());
    }
    else {
        return StringUtils.equals(a,b);
    }
}
</code>```

If all processes were defined externally, a change in process would not be all that difficult to correct and provided these more generic rules could be stored and categorized logically, they would be easy to find and would only need to change once as the business logic changes.

This approach seems relatively simple and straight forward. Why then, has it been generally rejected in favor of the typical object oriented coupling of data with methods?


问:
Regex to String generation
Let's say that we have a regex and an index i.  If we suppose that the set of strings that match our regex are sorted in a lexicographical order, how could we get the i element of this list?

Edit : I added this simple example for more explanation:

input :

```<code>regex="[a-c]{1,2}";
index=4;
</code>```

In this case the ordered list of strings that this regex matches contains the following  elements:

```<code>a
aa
ab
ac
b
ba
bb
bc
c
ca
cb
cc
</code>```

output :

The 4th element, which is ac

ps: It's known that a given regex could match an infinite number of strings.  This shouldn't have an impact on the process of extracting the element in the given finite index.

答:
kevin's answer was a good start to know how we can deal with regular expression from a theoritical point of view, which would help  building a java library that let users generate String based on a given regex . Here is a what i've build , a java library that provide many features for using regex to generate String (random generation ,generate String based on it's index, generate all String..) check it out here .

Example :

```<code>    Generex generex = new Generex("[0-3]([a-c]|[e-g]{1,2})");

    // generate the second String in lexicographical order that match the given Regex.
    String secondString = generex.getMatchedString(2);
    System.out.println(secondString);// it print '0b'

    // Generate all String that matches the given Regex.
    List<String> matchedStrs = generex.getAllMatchedStrings();

    // Using Generex iterator
    Iterator iterator = generex.iterator();
    while (iterator.hasNext()) {
        System.out.print(iterator.next() + " ");
    }
    // it print 0a 0b 0c 0e 0ee 0e 0e 0f 0fe 0f 0f 0g 0ge 0g 0g 1a 1b 1c 1e
    // 1ee 1e 1e 1f 1fe 1f 1f 1g 1ge 1g 1g 2a 2b 2c 2e 2ee 2e 2e 2f 2fe 2f 2f 2g
    // 2ge 2g 2g 3a 3b 3c 3e 3ee 3e 3e 3f 3fe 3f 3f 3g 3ge 3g 3g 1ee

    // Generate random String
    String randomStr = generex.random();
    System.out.println(randomStr);// a random value from the previous String list
</code>```

Title: Regex to String generation

Body:
kevin's answer was a good start to know how we can deal with regular expression from a theoritical point of view, which would help  building a java library that let users generate String based on a given regex . Here is a what i've build , a java library that provide many features for using regex to generate String (random generation ,generate String based on it's index, generate all String..) check it out here .

Example :

    Generex generex = new Generex("[0-3]([a-c]|[e-g]{1,2})");

    // generate the second String in lexicographical order that match the given Regex.
    String secondString = generex.getMatchedString(2);
    System.out.println(secondString);// it print '0b'

    // Generate all String that matches the given Regex.
    List<String> matchedStrs = generex.getAllMatchedStrings();

    // Using Generex iterator
    Iterator iterator = generex.iterator();
    while (iterator.hasNext()) {
        System.out.print(iterator.next() + " ");
    }
    // it print 0a 0b 0c 0e 0ee 0e 0e 0f 0fe 0f 0f 0g 0ge 0g 0g 1a 1b 1c 1e
    // 1ee 1e 1e 1f 1fe 1f 1f 1g 1ge 1g 1g 2a 2b 2c 2e 2ee 2e 2e 2f 2fe 2f 2f 2g
    // 2ge 2g 2g 3a 3b 3c 3e 3ee 3e 3e 3f 3fe 3f 3f 3g 3ge 3g 3g 1ee

    // Generate random String
    String randomStr = generex.random();
    System.out.println(randomStr);// a random value from the previous String list


问:
What kind of exception to ask for out of range arguments?
What type of exception should I throw?

I have a console class which describes rectangle of cells which a user can index by passing in a coordinate:

```<code>width, height = 80, 25
console = Console.new(width, height)

x, y = 2, 5
point_on_screen = Point.new(x, y)
console[point_on_screen] = 'a'
</code>```

I am now wondering what types of exception to throw when an index occurs out of bounds . That is, outside of the (constant!) domains x:[0, width] and y:[0, height]. I could throw a RangeError or an ArgumentError *.

Does it matter which type of exception to throw as long as the error message is useful?

Should I use the same exception type for both the construction of the console and the indexing? Are the two really semantically different?

* returning a kind of out of bounds object is possibly a better option - something like a Null Object Pattern - but not what I am wondering about here.

ArgumentError

One option is to throw an ArgumentError because the argument is obviously wrong, dimensions can never be non-negative. This is what I throw in example 1, because we ought to know in advance that the dimensions should be non-negative.

Example 1:

```<code>console = Console new(-3, 4) # Argument error
</code>```

RangeError

Another option is to throw a RangeError because the argument is out of the valid range. I use these for indexing. The argument is always out of range if x < 0, but if x ≥ 0 then it depends on the width of the console if the x is in the domain.

Example 2:

```<code>console = Console.new(20, 40)
pt = Point.new(-3, 4)
Console[pt] # RangeError
</code>```

答:
Does it matter which type of exception to throw as long as the error message is useful?

In cases like this, I often defer to the official docs for definitions and usage examples.

The docs for RangeError are a bit terse:

RangeError

  Raised when a given numerical value is out of range.

[1, 2, 3].drop(1 << 100)

  raises the exception:

  RangeError: bignum too big to convert into long

And although the docs for ArgumentError imply encouragement towards a more specific Exception, one of the examples (in bold below) certainly seems like a potential match for your use case:

ArgumentError

  Raised when the arguments are wrong and there isn't a more specific Exception class.

Ex: passing the wrong number of arguments

  [1, 2, 3].first(4, 5)

  raises the exception:

  ArgumentError: wrong number of arguments (2 for 1)

Ex: passing an argument that is not acceptable:

  [1, 2, 3].first(-4)

  raises the exception:

  ArgumentError: negative array size

Generally speaking, Argument-type exceptions are a clear and expected way to convey to the caller that they've supplied some invalid parameters.

Regarding your mention of "... as long as the message is helpful...", I say yes, absolutely. Always try to include a meaningful message when you raise an error.

Regarding the null object alternative: Personally, I'd encourage you to explicitly raise the error rather than return a null object (or some other out-of-bounds indicator). Code built with this pattern is plagued by constant null checks, and inevitably a null object will escape your safety nets and wreak unexpected havoc on your program.

When I'm working with software that routinely returns nulls or special values as a "something went wrong" indicator, I need to spend additional mental cycles to make sure I'm checking all responses, and that I'm looking for the right error flags. (But, convention is certainly a factor, so if you're working with an existing code base which uses the null object pattern, it might be best to continue.)

Here's some good additional reading about exceptions vs. error variables: Are error variables an anti-pattern or good design?

OwnerDisplayName: R. Peereboom


问:
What's the proper way of dealing with a global file path?
I don't have compilable code, because the code in question depends on a large function that's irrelevant to the question, but say I have the following scenario:

```<code>savePath = "C:\\..."

changePath1, changePath2 :: String -> String

changePath1 passedPath =
    'Do something with passedPath'

changePath2 =
    'Do something with savePath'

let newPath1 = changePath1 savePath in ...
let newPath2 = changePath2 in ...
</code>```

Is it more proper to set up functions like changePath1 (where the global path is passed in), or changePath2 (where it just internally uses the global path)
If the functions had a chance of processing more then 1 path, obviously I'd use changePath1, but in my current program, there is only 1 path to deal with, so it seems simpler to just have all the functions internally know the global path instead of constantly passing it in.

Thank you

答:
Do you foresee ever wanting to change the value of savePath? If so, it should be passed in as an argument to your functions. (Even though your functions would all only process a single path, you might want its value to be dynamic within the program.)

With a name like savePath I could foresee wanting to change that via a command-line argument or pulling it in from a configuration file -- while keeping a hard-coded default. In these cases having it as a global constant wouldn't work.

Personally I prefer to have things like that passed to my functions so that they're autonomous from the rest of the code, but that's me. (When passing things like that around as an argument to functions becomes too painful, you can employ the State or Reader monads to help, though that cuts down on the autonomy.)


问:
How are composite tables generally handled when there is no ORM tool available?
I am developing a Windows Runtime Component (C#) to be used in an HTML/JS frontend for a Windows Store App. Now, one of the requests is to have a database on the local system to store metadata about files that will be downloaded. After looking everywhere I have started using SQLite combined with the sqlite-net wrapper library.

This seems to be widely regarded as the best option but it is a serious hassle for me to get working. Perhaps my biggest problem with it is that it cannot map collection types to composite tables. This lead to me writing my own SQL queries for the entire database structure but this quickly turned out to be a very inconvenient solution.

To clarify, this is the situation I'm referring to:

```<code>class School {
    string Name { get; set; }
    List<Person> Students { get; set; }
}

class Person {
    int Id { get; set; }
    string Name { get; set; }
}
</code>```

For such a small example you could surely write the SQL queries for the three tables yourself but in the actual situation I have an object that holds several collections which in turn also hold collections several levels down.

Maybe I am spoiled by Entity Framework but it is hard to believe that either everyone uses basic models that only hold the (very) limited set of types supported by sqlite-net or everybody writes his own wrapper around it to account for models with some more complexity.

How are these situations handled generally? Am I overlooking some very easy solution?

答:
Well, lists of lists are handled by multiple select statements, then IDataReader.NextResult provides access to subsequent selects. You then build your lists of lists manually.

Another way to interpret the question is how to represent a composite object, and for that views are very handy, but they are read-only, can't insert or update a view.

Pseudocode inc, don't quote me.

```<code>sproc GetSchoolAndStudents(int schoolId) -- this is a stored procedure
{
    select ID, Name, Address, PhoneNumber, OtherSchoolData from School where ID = schoolId

    select ID, FirstName, LastName, DoB, Sex, HairColor, Grade from Student where SchoolID = schoolId
}

using(IDataReader reader = cmd.ExecuteReader())
{
    School school = null;
    while(reader.Read())
    {
         school = /* ADO.NET jazzhands */
    }
    if(reader.NextResult())
    {
        while(reader.Read())
        {
            school.Students.Add(new Student { /* ADO.NET jazzhands */ } );
        }
    }
}
</code>```

Body:
Well, lists of lists are handled by multiple select statements, then IDataReader.NextResult provides access to subsequent selects. You then build your lists of lists manually.

Another way to interpret the question is how to represent a composite object, and for that views are very handy, but they are read-only, can't insert or update a view.

Pseudocode inc, don't quote me.

sproc GetSchoolAndStudents(int schoolId) -- this is a stored procedure
{
    select ID, Name, Address, PhoneNumber, OtherSchoolData from School where ID = schoolId

    select ID, FirstName, LastName, DoB, Sex, HairColor, Grade from Student where SchoolID = schoolId
}

using(IDataReader reader = cmd.ExecuteReader())
{
    School school = null;
    while(reader.Read())
    {
         school = /* ADO.NET jazzhands */
    }
    if(reader.NextResult())
    {
        while(reader.Read())
        {
            school.Students.Add(new Student { /* ADO.NET jazzhands */ } );
        }
    }
}


问:
What is a helper? Is it a design pattern? Is it an algorithm?
Maybe a little tongue-in-cheek, but as I can't find this answer anywhere through Google, so to ensure Software Engineering has the answer:

What is a helper?

I have seen the name being used everywhere (module names, class names, method names), as if the semantics were deep and meaningful, but in the context of Computer Science (although I don't have a degree in it), I've never seen a description or definition anywhere!

Is it a design pattern? Is it an algorithm? I once worked on a program in which the module and class were both called somethingsomethinghelper (where somethingsomething was fairly generic too) and I promptly renamed it to something that made sense to me, but I feel like I'm missing something here!

答:
My company used to use the Base class / Helper class methodology where each object would have two classes.  You would have a Person class that contained all of the class properties and definitions and a PersonHelper class that contained all of the methods, SQL statements and Logic that manipulated the Person class.  This worked well for us because all of our applications use SQL statements to manipulate data and it was very easy for us to find and modify the SQL statements as needed.

We have since moved on and now put everything in the Person / Base class.  We quit using the Helper naming convention because we wanted to have less files in our projects.  Also, the length of some of the class names were getting out of control.  lol.

Not a great example but you get the idea.

```<code>s = CompanyName.PersonHelper.GetPerson()
s = CompanyName.Person.GetPerson()
</code>```

I'm not saying that using the helper naming convention is the perfect solution but it did work for us for a few years.

Body:
My company used to use the Base class / Helper class methodology where each object would have two classes.  You would have a Person class that contained all of the class properties and definitions and a PersonHelper class that contained all of the methods, SQL statements and Logic that manipulated the Person class.  This worked well for us because all of our applications use SQL statements to manipulate data and it was very easy for us to find and modify the SQL statements as needed.

We have since moved on and now put everything in the Person / Base class.  We quit using the Helper naming convention because we wanted to have less files in our projects.  Also, the length of some of the class names were getting out of control.  lol.

Not a great example but you get the idea.

s = CompanyName.PersonHelper.GetPerson()
s = CompanyName.Person.GetPerson()

I'm not saying that using the helper naming convention is the perfect solution but it did work for us for a few years.


答:
If a program is "small" does not matter. What matters is if your program is just a game or throwaway tool for yourself, or if you develop this for the production environment of your employer.

If the latter is the case, chances are high the program, even if it is initially "small", may be used for several years, and there will be a high chance that it has to be adapted to changing requirements. The latter means that sooner or later there will be a need for unit tests or regression tests. And functions which depend on global variables are inherently harder to test than pure functions, which should make the decision clear.

Title: What's the proper way of dealing with a global file path?

Body:
I don't have compilable code, because the code in question depends on a large function that's irrelevant to the question, but say I have the following scenario:

```<code>savePath = "C:\\..."

changePath1, changePath2 :: String -> String

changePath1 passedPath =
    'Do something with passedPath'

changePath2 =
    'Do something with savePath'

let newPath1 = changePath1 savePath in ...
let newPath2 = changePath2 in ...
</code>```

Is it more proper to set up functions like changePath1 (where the global path is passed in), or changePath2 (where it just internally uses the global path)
If the functions had a chance of processing more then 1 path, obviously I'd use changePath1, but in my current program, there is only 1 path to deal with, so it seems simpler to just have all the functions internally know the global path instead of constantly passing it in.

Thank you


答:
Is it typical to hardcode values? Yes. Most software is hastily written and never leaves the harddrive it is compiled on, so it doesn't matter.

However, if its software that other people are going to use and install, and you want to be able to configure where something is saved, it usually goes two different ways based on who is configuring it.

However the question isn't about these scenarios. The question is if it is typical for small programs to save to a path that is stored as a global variable as opposed to passing the value in.

My answer: Yes it is typical.


答:
Three words that should strike fear in the hearts of all programmers 'complex security scheme'. Whilst his scheme may be the best security implementation ever written, it's just as likely to be full of holes. I would always go for simple is better, even if it means writing a bit more code. Even the best code has bugs and if its to be used in government systems the code should be as robust as possible.

In a nutshell this is not good practice and likely to fail any serious code review.

Title: Is this a good practice or not?

Body:
I have a colleague who has come up with a way of 'genericizing' information from a database so that all his web application's drop-down lists can share the same object in his MVC.NET C# code and Views, which can contain different data depending on what tables it is being used against.

We work for a government agency, and we have facilities divided up into areas called "Regions", which contain further subdivided areas called VISNs, which each contain "Sites" or "Facilities". My colleague has developed a very complex security scheme whereby people can be granted access to data based on their permission level which can be assigned by Region, VISN, Site, or any mixture of the three. It's a nice scheme and very clever. However, he has stored procedures that return lists of Regions, VISNs, and Sites based on a person's User Id, and he is returning "generic" values like TextFieldID, TextField, and TextParentID. My first problem with this, is that looking at this data coming out of the database, I would not know what the data is. I feel that fields coming from a query or stored procedure should be descriptive of the data they are delivering. What does everyone else think? The deeper issue for me however is that he is taking some of the data, concatenating it in his stored procedure like this

SELECT DISTINCT
    t.VisnID,
    NULL,
    t.StationID,
    'V' + CAST(t.VisnID as varchar) + ': ' + t.Station3N + ': ' + t.StationName,
    t.Inactive
FROM Stations t
```

<p>and sending it back in a "TextField" property, instead of sending back the discrete data separately (<code>Station3N</code>, <code>StationName</code>) and concatenating it in the View, which would allow for different concatenation depending on what device what accessing the application (perhaps mobile and desktop). His justification is that he can send all his various drop down data and capture them all, regardless of content, in the same C# object named "LookupValue." </p>

```public partial class LookupValue : IEquatable<LookupValue>
{
    public LookupValue(string textFieldId, string textField, bool inactive)
    {
        TextFieldID = textFieldId;
        TextField = textField;
        Inactive = inactive;
    }

    public LookupValue(string textParentId, string textFieldId, string textField, bool inactive)
    {
        TextParentID = textParentId;
        TextFieldID = textFieldId;
        TextField = textField;
        Inactive = inactive;
    }

    public LookupValue(string textParentId, string textSelfParentId, string textFieldId, string textField, bool inactive)
    {
        TextParentID = textParentId;
        TextSelfParentID = textSelfParentId;
        TextFieldID = textFieldId;
        TextField = textField;
        Inactive = inactive;
    }

    ///
    /// Returns a custom string identifier if the Inactive property is true.
    ///
    public string GetInactiveString()
    {
        string value = "";
        if (Inactive)
        {
            value = "[I]";
        }

        return value;
    }

    ///
    /// Returns a custom text label that concatenates the TextField property with the custom string identifier of the Inactive property.
    ///
    public string GetDisplayNameWithInactiveString
    {
        get { return TextField + " " + GetInactiveString(); }
    }

    public bool Equals(LookupValue other)
    {
        //Check whether the compared object is null.
        if (Object.ReferenceEquals(other, null)) return false;

        //Check whether the compared object references the same data.
        if (Object.ReferenceEquals(this, other)) return true;

        //Check whether the products' properties are equal.
        return TextFieldID.Equals(other.TextFieldID) && TextField.Equals(other.TextField);
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.
    public override int GetHashCode()
    {
        //Get hash code for the TextFieldID field if it is not null.
        int hashTextFieldId = TextFieldID == null ? 0 : TextFieldID.GetHashCode();

        //Get hash code for the Code field.
        int hashTextField = TextField.GetHashCode();

        //Calculate the hash code for the product.
        return hashTextFieldId ^ hashTextField;
    }
}
```

He believes the re-usability of this object is worth the violation of Separation of Concerns and possible future difficulties in handling more than one display variation for a drop-down. I should point out that this object is contained in his Data project namespace (our projects are separated into Data, Web, Services, etc.) instead of the Web project namespace and he also returns this object to the Web layer via his Repository queries which call the stored procedures that I described earlier,  which is gross violation of Separation of Concerns in my opinion.

I am just looking for some confirmation from other programmers that this is in fact a bad practice, and also looking for ideas I can present him on better ways to do what he is attempting. I have my own ideas, but again I'm just looking for other's ideas so I have more options to present to him.

--Edit -- I forgot to mention that we are using Entity Framework as an ORM, and his Repository classes in his DAL are dumping the data from the stored procs into this LookupValue object.


问:
What do you use string reversal for?
In PHP it's strrev(), in Rails it's .reverse, but most languages don't have any string reverse function. Some have array reverse functions that can be used on characters. I was thinking this must be a major oversight but then it occurred to me, what would you actually use string reverse for???

The only time I can think I've seen it is in demos and lessons to turn "Hello World!" into "!dlroW olleH".

My question is; Is there a use for reversing a string or is it completely pointless?

.

Addendum

There have been way more answers that I had anticipated and not all of them were entirely academic. I would have put money that no one could come up with a legitimate example. I also didn't think I would learn anything new but Mark Canlas' regex suggestion is just brilliant and I look forward to the opportunity for it to prove itself. Thanks to all.

答:
I have been a coder/developer/sysadmin for ~10 years and I cannot remember ever needing string reversal in real life situations.

The only immediate use-case that I can think of is number base conversion: done naively, the procedure returns a reversed string. However, with a bit of math, you can compute upfront the amount of space needed, so you can start filling the buffer from the end.

Title: What do you use string reversal for?


答:
If there is no ORM available, and writing all SQLs manually becomes too tedious, why not write a simple SQL code generator for the queries? This is simpler as it may look at a first glance. I know this for sure, since we did this around 10 years ago, when C# was new and there was no usable ORM available for .NET at that time.

Create a C# assembly with "naked" class definitions only, for the purpose of providing the relevant input for your code generator (so you don't have to create any kind of parser). Use  reflection to grab the information from that assembly, to generate the real class definitions, including all CRUD code/SQL. Define some class attributes for any missing meta information (for example, about the relations between your classes and the needed composite tables). It may also turn helpful to have a consistent convention about technical primary keys (for example, let the primary keys be always of the form "class name" + ID).

Since you have only a medium size data model, you only have to support a limited list of data types and can design the code generator to follow the conventions of your project. This is a little bit like writing your own ORM, but with much less effort, since it does not have to work for many general cases and different DB systems, only for the handful cases of your project, and only for SqLite-net.

Title: How are composite tables generally handled when there is no ORM tool available?

Body:
I am developing a Windows Runtime Component (C#) to be used in an HTML/JS frontend for a Windows Store App. Now, one of the requests is to have a database on the local system to store metadata about files that will be downloaded. After looking everywhere I have started using SQLite combined with the sqlite-net wrapper library.

This seems to be widely regarded as the best option but it is a serious hassle for me to get working. Perhaps my biggest problem with it is that it cannot map collection types to composite tables. This lead to me writing my own SQL queries for the entire database structure but this quickly turned out to be a very inconvenient solution.

To clarify, this is the situation I'm referring to:

```<code>class School {
    string Name { get; set; }
    List<Person> Students { get; set; }
}

class Person {
    int Id { get; set; }
    string Name { get; set; }
}
</code>```

For such a small example you could surely write the SQL queries for the three tables yourself but in the actual situation I have an object that holds several collections which in turn also hold collections several levels down.

Maybe I am spoiled by Entity Framework but it is hard to believe that either everyone uses basic models that only hold the (very) limited set of types supported by sqlite-net or everybody writes his own wrapper around it to account for models with some more complexity.

How are these situations handled generally? Am I overlooking some very easy solution?


答:
I'm going to start flat out by saying after more than 30 years experience writing software and working in I.T in general, I have NEVER, EVER yet found a good reason for concatenating data coming out of a database.

You could be putting 90% of your application code in the DB infrastructure, and doing all sorts of magic things with it, and I still would not be persuaded that it's ever a good idea.

As has been hinted already, databases are designed for one specific task, and one specific task only, storing, searching, retrieving and general management of data.

The meta data, indexes, clusters and everything else a DBMS does well are there to ensure that it does its job with the best efficiency possible, and if you try to circumvent that, you're gonna land yourself in a whole heap of trouble.

Look at it this way - would you attempt to take your own C# code, and compile it by hand, to get better results than the compiler? Could you even get better results? I doubt it, in the same token creating your own data scheme is reckless and irresponsible IMHO.

That said, maybe your colleague has his reasons. There may, as others have said, be factors you're not privy to.

What he needs to consider is not only the ramifications of his en-devour on current affairs, but what it holds for the future.

Things like:

1) Future maintenance.  Will he be still there in 10 years, or even 1 year for that matter?  If not, who's going to maintain it?

2) If he does leave, and he leaves under bad circumstances, will someone get trained in how his system works?  Or will upper management just assume that everyone who worked with him understands this code? (Take it from me, I've been in this position quite a few times, it's not funny when you don't have the first clue what you're looking at.)

3) What happens if the HTML spec changes in such a way that his concatenation breaks future revisions (because he concatenates using some protected character sequence for example), or what if future spec changes break his concatenation? (This scenario has already happened more times than you might realize.)

4) If your database server goes down in a ball of flames, which is easier to recover? A standards compliant database structure that everyone understands, or a hideously obfuscated 3 headed mess of stored procs and custom data schemes? (I know which I'd pick.)

I could sit here and give you a dozen more reasons easily, but I'm not going to.

Instead, I'm going to propose what just might be way out, that keeps you both happy.

He might be doing things this way because he doesn't know better.

You mention he's more of a DBA than a DEV, and that's fine, I've worked with many guys who are amazing DBA's but put a compiler in front of them and they'll curl up a ball and start to cry, and will happily admit their lack of knowledge.

Likewise, I've worked with DBA's who are so utterly stubborn and blind to their way of doing things for whatever reason, that they'll enforce that structure all the way down the line, often because they don't really understand what's happening beyond the DBA, but like many of us don't want to admit it (Human nature, is what it is...)

Whichever way you look at it, he's not going to budge, and you're not going to be happy until your "do it correctly, inner dev" is pacified.

What you need is a compromise.

In my mind, you can easily achieve this compromise using views.

See if you can get him to put all his logic into a set of views, then the code that needs this approach can query those, just as easily as it queries existing tables and/or stored procs.

This way, the actual table definitions, remain in a pristine condition with separate columns, so you can write standard, compliant ORM based code against them.

I've used this approach very successfully in the past for a not too dissimilar scenario, where I was tasked with creating an application to process some geographic data.

In my particular case, I needed to get some data back from a DB table, but this table had already been pre-processed in the back-end to return the data in a format suitable for another app.  My solution here was to transform that data back to what was needed for my task, using a view.

Doing this, kept the original interface, and program code working, but it gave me the flexibility to change things for the better in the slice of the work I needed to do.

If you can't take this approach at the DB level, because for example he controls the DB and its access, then you may have to resort to other tricks.

If you're working in C# as you say you are, then it's not difficult to hook the code in different modules.

.NET code, whatever language it's written in, is compiled down to simple MSIL, and there are dozens of ways of injecting your own code in there to replace anything that's already running.

Robert Harvey above mentioned using a product like Automapper.

This is a quite reasonable suggestion, but one you'll want to give some thought to.

I use Automapper all the time, and it's good at the job it's designed for.  That job is passing and matching DTO's between layers in your N-Tier design.

Automapper is typically used to flatten and combine multiple DTO's into a single level view model, typically for use in a presentation layer driven pattern such as MVC or MVVM.

In this particular case however, I don't quite see how Automapper might help you. AM is conventions based.  This means that if you have, say, an EF object on one side that looks like this:

```<code>public class EFobject
{
  public string name { get; set; }
  public string email { get; set; }
  public string dept { get; set; }
}
</code>```

and a regular POCO on the other side that looks like this:

```<code>public class RegularPoco
{
  public string name { get; set; }
  public string email { get; set; }
}
</code>```

Automapper will ensure that the name and email fields get copied across, but will ignore the dept field.

If you were concatenating the strings at the code level, then you could easily use Automapper to produce the same result your colleague is generating, by specifying mapping rules that took those three columns, and pushed them into one column with the ':' symbol between each. Breaking them apart, however, AM is the wrong tool for the job.

Another option you have, is to handle this in your business layer.

If you're following good N-Tier architecture and design principles, then at an absolute minimum, you should have 'Presentation', 'Business Rules' and 'Data' layers.

Myself personally, I usually separate my DTO's and View models out into distinct layers too, but that's just to aid the way I work in Visual Studio.

With a business rules layer, nothing makes it to the presentation layer without first going through that layer, and at that point you have the entire .NET eco-sphere at your disposal to break that string apart again.

However, as you point out, that's no help when you don't know what the original data was, so you have one other possible approach to dealing with this.

If you can't break him of his habit, and he resists change, then use "Praise based change".

Praise him on his approach, and appear to be helpful, suggest "Improving" on his way of doing things by adding in data you can digest at the Business rules layer. For example, get him to change the output from something like:

```<code>1234:station1:fred
</code>```

to

```<code>1234(stationid,int):station1(stationref,string):fred(stationname,string)
</code>```

in his select driven obsession he can then simply pass things through a simple search and replace that removes anything in the brackets including said brackets, but... gives you all the information you need to de-serialize this thing back into a regular POCO.

Out of everything I've outlined here, I really wouldn't recommend going this route however, but sometimes you just have no choice but to go with the flow, and improvements for the greater good of your task are sometimes the only effective weapon you have.

In summary:

Standards and patterns & practices exist for a reason, and that reason extends way beyond initial development into the ALM Cycle until the product is eventually replaced.

I've come across so many DBA's (and devs for that matter) over the years who just can't see this bigger picture beyond finishing the list of tickets they have to work on, that it scares the living daylights out of me.

Team members should never be looking for ways to do things bigger & better than everyone else. Instead, you should always be looking for common ground, and common sense.

As one of the other posters above put it: simplicity is always the best option , never forget what KISS stands for, because one fine day when the S**t hits the fan, it might just be KISS that saved you from getting well and truly roasted.

Title: Is this a good practice or not?

Body:
I'm going to start flat out by saying after more than 30 years experience writing software and working in I.T in general, I have NEVER, EVER yet found a good reason for concatenating data coming out of a database.

You could be putting 90% of your application code in the DB infrastructure, and doing all sorts of magic things with it, and I still would not be persuaded that it's ever a good idea.

As has been hinted already, databases are designed for one specific task, and one specific task only, storing, searching, retrieving and general management of data.

The meta data, indexes, clusters and everything else a DBMS does well are there to ensure that it does its job with the best efficiency possible, and if you try to circumvent that, you're gonna land yourself in a whole heap of trouble.

Look at it this way - would you attempt to take your own C# code, and compile it by hand, to get better results than the compiler? Could you even get better results? I doubt it, in the same token creating your own data scheme is reckless and irresponsible IMHO.

That said, maybe your colleague has his reasons. There may, as others have said, be factors you're not privy to.

What he needs to consider is not only the ramifications of his en-devour on current affairs, but what it holds for the future.

Things like:

1) Future maintenance.  Will he be still there in 10 years, or even 1 year for that matter?  If not, who's going to maintain it?

2) If he does leave, and he leaves under bad circumstances, will someone get trained in how his system works?  Or will upper management just assume that everyone who worked with him understands this code? (Take it from me, I've been in this position quite a few times, it's not funny when you don't have the first clue what you're looking at.)

3) What happens if the HTML spec changes in such a way that his concatenation breaks future revisions (because he concatenates using some protected character sequence for example), or what if future spec changes break his concatenation? (This scenario has already happened more times than you might realize.)

4) If your database server goes down in a ball of flames, which is easier to recover? A standards compliant database structure that everyone understands, or a hideously obfuscated 3 headed mess of stored procs and custom data schemes? (I know which I'd pick.)

I could sit here and give you a dozen more reasons easily, but I'm not going to.

Instead, I'm going to propose what just might be way out, that keeps you both happy.

He might be doing things this way because he doesn't know better.

You mention he's more of a DBA than a DEV, and that's fine, I've worked with many guys who are amazing DBA's but put a compiler in front of them and they'll curl up a ball and start to cry, and will happily admit their lack of knowledge.

Likewise, I've worked with DBA's who are so utterly stubborn and blind to their way of doing things for whatever reason, that they'll enforce that structure all the way down the line, often because they don't really understand what's happening beyond the DBA, but like many of us don't want to admit it (Human nature, is what it is...)

Whichever way you look at it, he's not going to budge, and you're not going to be happy until your "do it correctly, inner dev" is pacified.

What you need is a compromise.

In my mind, you can easily achieve this compromise using views.

See if you can get him to put all his logic into a set of views, then the code that needs this approach can query those, just as easily as it queries existing tables and/or stored procs.

This way, the actual table definitions, remain in a pristine condition with separate columns, so you can write standard, compliant ORM based code against them.

I've used this approach very successfully in the past for a not too dissimilar scenario, where I was tasked with creating an application to process some geographic data.

In my particular case, I needed to get some data back from a DB table, but this table had already been pre-processed in the back-end to return the data in a format suitable for another app.  My solution here was to transform that data back to what was needed for my task, using a view.

Doing this, kept the original interface, and program code working, but it gave me the flexibility to change things for the better in the slice of the work I needed to do.

If you can't take this approach at the DB level, because for example he controls the DB and its access, then you may have to resort to other tricks.

If you're working in C# as you say you are, then it's not difficult to hook the code in different modules.

.NET code, whatever language it's written in, is compiled down to simple MSIL, and there are dozens of ways of injecting your own code in there to replace anything that's already running.

Robert Harvey above mentioned using a product like Automapper.

This is a quite reasonable suggestion, but one you'll want to give some thought to.

I use Automapper all the time, and it's good at the job it's designed for.  That job is passing and matching DTO's between layers in your N-Tier design.

Automapper is typically used to flatten and combine multiple DTO's into a single level view model, typically for use in a presentation layer driven pattern such as MVC or MVVM.

In this particular case however, I don't quite see how Automapper might help you. AM is conventions based.  This means that if you have, say, an EF object on one side that looks like this:

public class EFobject
{
  public string name { get; set; }
  public string email { get; set; }
  public string dept { get; set; }
}

and a regular POCO on the other side that looks like this:

public class RegularPoco
{
  public string name { get; set; }
  public string email { get; set; }
}

Automapper will ensure that the name and email fields get copied across, but will ignore the dept field.

If you were concatenating the strings at the code level, then you could easily use Automapper to produce the same result your colleague is generating, by specifying mapping rules that took those three columns, and pushed them into one column with the ':' symbol between each. Breaking them apart, however, AM is the wrong tool for the job.

Another option you have, is to handle this in your business layer.

If you're following good N-Tier architecture and design principles, then at an absolute minimum, you should have 'Presentation', 'Business Rules' and 'Data' layers.

Myself personally, I usually separate my DTO's and View models out into distinct layers too, but that's just to aid the way I work in Visual Studio.

With a business rules layer, nothing makes it to the presentation layer without first going through that layer, and at that point you have the entire .NET eco-sphere at your disposal to break that string apart again.

However, as you point out, that's no help when you don't know what the original data was, so you have one other possible approach to dealing with this.

If you can't break him of his habit, and he resists change, then use "Praise based change".

Praise him on his approach, and appear to be helpful, suggest "Improving" on his way of doing things by adding in data you can digest at the Business rules layer. For example, get him to change the output from something like:

1234:station1:fred

to

1234(stationid,int):station1(stationref,string):fred(stationname,string)

in his select driven obsession he can then simply pass things through a simple search and replace that removes anything in the brackets including said brackets, but... gives you all the information you need to de-serialize this thing back into a regular POCO.

Out of everything I've outlined here, I really wouldn't recommend going this route however, but sometimes you just have no choice but to go with the flow, and improvements for the greater good of your task are sometimes the only effective weapon you have.

In summary:

Standards and patterns & practices exist for a reason, and that reason extends way beyond initial development into the ALM Cycle until the product is eventually replaced.

I've come across so many DBA's (and devs for that matter) over the years who just can't see this bigger picture beyond finishing the list of tickets they have to work on, that it scares the living daylights out of me.

Team members should never be looking for ways to do things bigger & better than everyone else. Instead, you should always be looking for common ground, and common sense.

As one of the other posters above put it: simplicity is always the best option , never forget what KISS stands for, because one fine day when the S**t hits the fan, it might just be KISS that saved you from getting well and truly roasted.

ContentLicense: CC BY-SA 4.0