Procedural, not OO

Take this simple class

public class Foo
{
     public int SomeInt { get; set; }
     public string SomeString { get; set; }
     public Bar SomeBar { get; set; }

     public void DoSomeWork()
    {
        SomeString.Append(" Blah Blah");
        SomeBar.BarMethod();
    }
}

And initialise it like this:

var foo = new Foo
               {
                    SomeInt = 1,
                    SomeString = "I'm a string",
                    SomeBar = new Bar()
               };
foo.DoSomeWork();

This is not Object orientated programming. It's actually very procedural. The problem with this snippet should be obvious - even though the code will work you should steer well clear of this!

You will probably look at this snippet and think it's silly, “of course this is bad!”. But I see this type of code a lot.

What’s the problem with this?

This code will straight up break if you don’t give the Foo object a Bar object. You might be tempted to argue “Well, give it a Bar object before you call Foo.DoSomeWork();

no.

Pass in your dependencies - Declare that this class can only be used one way.

If another developer comes along who wants to use your Foo class, they don’t know what a Foo object needs in order to work. He/she would presume it doesn’t need anything at all because of the parameter less constructor.

What then?

public class SomeClass
{     
	public SomeClass(int someInt, string someString, Bar bar)
    {
    	if (bar == null)
        	throw new ArgumentNullException("bar");

		SomeInt = someInt;
        SomeString = someString;
        SomeBar = bar;
    }
    
    public int SomeInt { get; private set; }
    public string SomeString { get; private set; }
    public Bar SomeBar { get; private set; }
    
    public void DoSomeWork()
    {
    	SomeString.Append(" Blah Blah");
        SomeBar.BarMethod();
    }
}

Here you are specifically saying - "In order for me to work, I need these 3 things."

There are exceptions to this case, Dto's for example. Overall we should keep tight encapsulation of our classes. Think private first and expose as needed, rather than taking an 'everything public except things that shouldn't be' outlook.

This is Object Orientated programming 101 - only I see it too often.