Is this question really that difficult?

Hmongkeysauce

Senior member
Jun 8, 2005
360
0
76
See the code below. A friend of mine failed this question during an interview for a .NET programming position. The interviewer told him that many candidates failed the question as well. I thought it was pretty straight forward. But I could be wrong. What do you guys think?

Code:
        static void Main(string[] args)
        {
            StringBuilder str = new StringBuilder("Hello World");
            GoodDay(str);
            Console.WriteLine(str.ToString());
            BadDay(str);
            Console.WriteLine(str.ToString());
	
        }

        private static void GoodDay(StringBuilder str)
        {
            str.Append(" – It is a good day today.");
        }
        private static void BadDay(StringBuilder str)
        {
            str = new StringBuilder(" – It is a bad day today.");
        }
 

BrightCandle

Diamond Member
Mar 15, 2007
4,762
0
76
Its pretty straight forward, its just testing peoples understanding of object passing by value and reference. I guess to some extent it needs some knowledge of StringBuilder to answer it, the class could in theory be immutable so wouldn't change the object. The API signature for Append isn't clear either since it returns a StringBuilder, but the examples given in the docs prove the class is not immutable.

Not a question any programmer today (regardless of language) should be failing.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
Its pretty straight forward, its just testing peoples understanding of object passing by value and reference. I guess to some extent it needs some knowledge of StringBuilder to answer it, the class could in theory be immutable so wouldn't change the object. The API signature for Append isn't clear either since it returns a StringBuilder, but the examples given in the docs prove the class is not immutable.

Not a question any programmer today (regardless of language) should be failing.

Maybe my C# is getting rusty. Does the mutability really matter? Seems to me the main point is what does 'str' refer to in the scope of Main() after the call to BadDay (or put another way, what is being assigned to in BadDay). Without knowing anything about the thing being passed other than that it is a reference type, it should be easy to answer that question.
 
Last edited:

BrightCandle

Diamond Member
Mar 15, 2007
4,762
0
76
The mutability matters a great deal. If StringBuilder isn't mutable then GoodDay doesn't do anything, otherwise it modifies the StringBuilder and adds the good day string, which the combination of which then gets written out on the console.

BadDay is although about pass by value semantics and whether a method can change the reference outside of its scope (which is definitely possible in some languages).

I don't consider either tough topics, you need to understand both to answer the question properly.
 

WaitingForNehalem

Platinum Member
Aug 24, 2008
2,497
0
71
Why does the GoodDay function modify str in the main function if it is being passed by value? Is it because str.Append returns the instance?
 

Paul98

Diamond Member
Jan 31, 2010
3,732
199
106
Nothing hard about it, I am guessing people just run into a problem thinking StringBuilder will function similar to String in that situation.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
The mutability matters a great deal. If StringBuilder isn't mutable then GoodDay doesn't do anything, otherwise it modifies the StringBuilder and adds the good day string, which the combination of which then gets written out on the console.

BadDay is although about pass by value semantics and whether a method can change the reference outside of its scope (which is definitely possible in some languages).

I don't consider either tough topics, you need to understand both to answer the question properly.

Ah good point, I wasn't thinking about GoodDay. I figured the whole point of the exercise was the parameter passing semantics and reference vs. value types. A lot of candidates I've interviewed for ASP dev positions wouldn't get this question. The difference between an object and a reference to an object, and passing a reference by value vs. passing an object by value, eludes them.
 

Hmongkeysauce

Senior member
Jun 8, 2005
360
0
76
The mutability matters a great deal. If StringBuilder isn't mutable then GoodDay doesn't do anything, otherwise it modifies the StringBuilder and adds the good day string, which the combination of which then gets written out on the console.

BadDay is although about pass by value semantics and whether a method can change the reference outside of its scope (which is definitely possible in some languages).

I don't consider either tough topics, you need to understand both to answer the question properly.

Good catch. I merely pointed him to value vs reference topics and stack and heap topics to answer this question.
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
GoodDay() appends to the passed string builder, so it first prints "Hello World - It is a good day today."

The BadDay function creates a new string builder and sets the local 'str' variable to it. This doesn't modify the existing string builder in the main method, so the second writeline also prints "Hello World - It is a good day today."

Edit: got time warped and became the first post. Hmongkeysauce is the OP.
 
Last edited:

KB

Diamond Member
Nov 8, 1999
5,396
383
126
I think people fail it because it is written to "trick" people who aren't paying enough attention. Although I have seen this problem asked many times and knew the answer, I failed it at first because I wasn't giving it my full thoughts.

My brain rewrote the code like this, as I am assuming your friend did too.
Code:
        static void Main(string[] args)
        {
            StringBuilder str = new StringBuilder("Hello World");
            GoodDay(str);
            Console.WriteLine(str.ToString());
            BadDay(ref str);
            Console.WriteLine(str.ToString());

        }

        private static void GoodDay(StringBuilder str)
        {
            str.Append(" &#8211; It is a good day today.");
        }
        private static void BadDay(ref StringBuilder str)
        {
            str = new StringBuilder(" &#8211; It is a bad day today.");
        }

I am not overly interested in a programmer who knows every nuance of a language. I am more looking for someone who writes readable and understandable simple code.
Any programmer that wrote code like this, even though its valid would have to be retrained IMHO. I think a good programmer would write it like this, which would make any question about what is going on null and void.

Code:
    class Program
    {
        static void Main(string[] args)
        {
            Day d = new Day("Hello World");
            d.SetGood();
            Console.WriteLine(d.ToString());
            d.SetBad();
            Console.WriteLine(d.ToString());
            Console.Read();
        }

    }

    public class Day
    {
        public Day(string s){
            str = new StringBuilder("Hello World");
        }

        private StringBuilder str = new StringBuilder();

        public void SetGood()
        {
            str.Append(" &#8211; It is a good day today.");
        }

        public void SetBad()
        {
            str = new StringBuilder(" &#8211; It is a bad day today.");
        }

        public override string ToString()
        {
            return str.ToString();
        }
    }
 

Tweak155

Lifer
Sep 23, 2003
11,448
262
126
GoodDay() appends to the passed string builder, so it first prints "Hello World - It is a good day today."

The BadDay function creates a new string builder and sets the local 'str' variable to it. This doesn't modify the existing string builder in the main method, so the second writeline also prints "Hello World - It is a good day today."

Edit: got time warped and became the first post. Hmongkeysauce is the OP.

Given that I know almost nothing about C#, why is BadDay a local variable but GoodDay a referenced variable?
 

BrightCandle

Diamond Member
Mar 15, 2007
4,762
0
76
Given that I know almost nothing about C#, why is BadDay a local variable but GoodDay a referenced variable?

c# passes object references by value just like Java. What this means is that the reference to the object is copied when its passed into the method, so changing it to refer to a different object wont change what Main is using. However its only copied the reference, both Main and GoodDay are pointing at the same object. Since StringBuilder can be mutated this allows GoodDay to change the state of the common object they can both see.

Thus the question depends not only on understanding the pass by copy semantics but also that its 1 object being referred to and that it must be mutable in order to communicate outside of the scope of the method.

Personally I would write this in an immutable way instead, then it would suffer none of these problems and would isolate the side effects to the Main method, then it would be much clearer and with no chance of misunderstanding what it does. This example shows just why mutable adjustment of objects in methods like this is inherently non obvious and has poor transparency.
 

Tweak155

Lifer
Sep 23, 2003
11,448
262
126
c# passes object references by value just like Java. What this means is that the reference to the object is copied when its passed into the method, so changing it to refer to a different object wont change what Main is using. However its only copied the reference, both Main and GoodDay are pointing at the same object. Since StringBuilder can be mutated this allows GoodDay to change the state of the common object they can both see.

Thus the question depends not only on understanding the pass by copy semantics but also that its 1 object being referred to and that it must be mutable in order to communicate outside of the scope of the method.

Personally I would write this in an immutable way instead, then it would suffer none of these problems and would isolate the side effects to the Main method, then it would be much clearer and with no chance of misunderstanding what it does. This example shows just why mutable adjustment of objects in methods like this is inherently non obvious and has poor transparency.

How do you make a class immutable vs mutable in C#?

EDIT:

May sound stupid, but I work in a language that doesn't even have default constructors like what is used in the example. I only recognize it from my college C++ days...
 
Last edited:

Tweak155

Lifer
Sep 23, 2003
11,448
262
126
From what I gather doing a quick google search, the following:
Code:
            string newStr = "This is a new str"; 
            newStr = "Modified NewStr";

Sets memory and stores "This is a new str" and the following line will then create new memory and "forget" the previously allocated memory, although it is off somewhere in space? This is because string class is immutable. That concept seems odd to me without specifying new memory.

On top of that, why don't I have to set memory for the String class at / after declaration, but I do for the StringBuilder class?
 

purbeast0

No Lifer
Sep 13, 2001
52,855
5,727
126
the thing about stupid questions like this though, is that in the real world, if you try it one way and it doesn't work, you simply go back and change it to the way that does work. it will be like a 1 minute blip in your work, and it is probably something you won't forget the next time.
 

BrightCandle

Diamond Member
Mar 15, 2007
4,762
0
76
the thing about stupid questions like this though, is that in the real world, if you try it one way and it doesn't work, you simply go back and change it to the way that does work. it will be like a 1 minute blip in your work, and it is probably something you won't forget the next time.

Its not a good way to program. If something fails you should know why it fails before you change it. If you just throw random things until it works that doesn't mean you have happened upon a bug free solution, it means you don't understand why any of the things passed or failed but this one looks better. A lot of bugs get written this way.

Its not the only thing to test, there are a lot of semantics like equality and hashcodes that poor developers also have misunderstandings about. My own experience of setting interviews on these sorts of questions were about 80% of developers who apply for jobs (some paying £150k a year!) fail to pass such simple tests. If you can't immediately see the problems that are being tested in the Ops code and get the correct answer then I wouldn't hire you.
 

purbeast0

No Lifer
Sep 13, 2001
52,855
5,727
126
Its not a good way to program. If something fails you should know why it fails before you change it. If you just throw random things until it works that doesn't mean you have happened upon a bug free solution, it means you don't understand why any of the things passed or failed but this one looks better. A lot of bugs get written this way.

Its not the only thing to test, there are a lot of semantics like equality and hashcodes that poor developers also have misunderstandings about. My own experience of setting interviews on these sorts of questions were about 80% of developers who apply for jobs (some paying £150k a year!) fail to pass such simple tests. If you can't immediately see the problems that are being tested in the Ops code and get the correct answer then I wouldn't hire you.

i'm not saying to throw random things around until they work, i'm saying if it does fail, most competent people can understand why within 5 minutes and then figure out the right solution. there is a difference between that and just trying random crap till something works and moving on.

as long as someone could explain why badday is a terrible function, that is good enough for me lol.
 

Tweak155

Lifer
Sep 23, 2003
11,448
262
126
i'm not saying to throw random things around until they work, i'm saying if it does fail, most competent people can understand why within 5 minutes and then figure out the right solution. there is a difference between that and just trying random crap till something works and moving on.

as long as someone could explain why badday is a terrible function, that is good enough for me lol.

From my experience this isn't true. The majority of developers I've worked with just want it to work and don't care why it fails.

Perhaps most developers aren't competent and it just lines up with both your statements lol.
 

purbeast0

No Lifer
Sep 13, 2001
52,855
5,727
126
From my experience this isn't true. The majority of developers I've worked with just want it to work and don't care why it fails.

Perhaps most developers aren't competent and it just lines up with both your statements lol.

i'm glad i now know that i've worked with some good people over the years if that is the majority of developers you all have worked with lol.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
Personally I would write this in an immutable way instead, then it would suffer none of these problems and would isolate the side effects to the Main method, then it would be much clearer and with no chance of misunderstanding what it does. This example shows just why mutable adjustment of objects in methods like this is inherently non obvious and has poor transparency.

I'm curious as to what an immutable string builder class would look like. The explicit contract promise is that you can build a string from a set of strings, and the implicit promise is that it will be more efficient than just concatenating strings and living with the interim copies getting created and thrown away. So how do you make a string builder with immutable internal state?
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
This example shows just why mutable adjustment of objects in methods like this is inherently non obvious and has poor transparency.

Was reading this again and wanted to expand on this statement, which I find interesting and perplexing. The idea of the superiority of immutable state comes up all the time in discussions of functional languages. I understand what it means in abstract, I think, but I am completely object-oriented in my concepts from the brain-stem out, so I struggle to get what it _really_ means in a world of real systems where every object is not the encapsulation of the output from some previous function waiting to be transformed by the next function in the chain.

A StringBuilder is meant to build a string. Isn't the very notion of "building" something inextricably bound up with the idea of changing state? Why would anyone expect a StringBuilder to be immutable when passed into another method, unless you were working in a language where the method signature could specify that the object would be treated as a const? Why is it inherently non-obvious that it could be used to build a string? Furthermore, isn't passing a StringBuilder around so that various methods could add parts to it an analog for passing, say, a logger around so that various methods could log to it? Would anyone expect a logger to be immutable?

I know I must be missing something, because stateless functional programming is a major topic of interest on Hacker News, but how the hell do you create an actual system in that way?
 

Cogman

Lifer
Sep 19, 2000
10,277
125
106
I'm curious as to what an immutable string builder class would look like. The explicit contract promise is that you can build a string from a set of strings, and the implicit promise is that it will be more efficient than just concatenating strings and living with the interim copies getting created and thrown away. So how do you make a string builder with immutable internal state?

Make the only method to that string builder a List/array/whatever of strings. It sort of defeats the purpose, but whatever.


In other words, it would look something like this

String str = Stringbuilder.build(["I ", "like ", "cats]);

No state needed and it SHOULD be faster than straight string concatenation.