views:

1346

answers:

18

How do I explain loose coupling and information hiding to a new programmer? I have a programmer who I write designs for, but who can't seem to grasp the concepts of loose coupling and information hiding.

I write designs with everything nicely broken down into classes by function (data access is separate, a class for requests, a controller, about 5 classes total). They come back with a modified design where half the classes inherit from the other half (and there is no "is-a" relationship), and many public variables.

How can I get across the idea that keeping things separate makes it easier to maintain?

+7  A: 

Theory will only get you so far.

Make him try to add new features to code he's written a while ago. Then rework the old code with him so it's loosely coupled and ask him to add the same features.

He will certainly understand the avantages of writing good code.

dub
+10  A: 

The best way to explain these kinds of concepts is to use analogies. Pick something non-programming related and use that to explain the abstract design concepts.

This image is pretty good at explaining the need for loose coupling. Try to come up with stuff like this that will amuse and pertain to your new programmer.

Andrew Hare
In my experience the bad use of analogies is the No1 reason why so many people don't get inheritance. Be very careful that the anaogies you use are good ones.
Martin Brown
i don't get it..
Andreas Petersson
+46  A: 

Ask him if it's a good idea to let you borrow $10 by giving his wallet to you for a moment and taking the money yourself.

Boris Pavlović
Hey mate, just thought I'd say that it's "lend" not "borrow" :)
Robert Grant
Hahaha, great way to put it :-)
unforgiven3
Great, but he can respond : "I trust you !" ;p
Nicolas Dorier
Then, replace 'you' with 'anyone'!
David
@Robert: I don't know if the syntax was modified in other ways, but reading the sentence as it is now, it should be "borrow" not "lend."
R. Bemrose
I wish I could vote this one up twice.
Christopher W. Allen-Poole
I'm with the bard on this one "Neither a borrower nor a lender be".
kjack
+1 Man that's an awesome answer
cletus
+1  A: 

Show him this presentation. Though it's mainly about DI, it's downright brilliant and up to the point.

Anton Gogolev
+1  A: 

I would try sitting down with him and working through a couple of peieces of code with him looking over your sholder and you explaining why you are doing what you are doing as you go along. I've found this is normally the best way to explain things.

Martin Brown
A: 

Well if you have to explain it to them then I'm forced to ask: are they really a programmer?

Tell them they need a "college do over"?

That's a hard one because it's such a basic concept. Personally I wouldn't want to handle it because it's like someone is getting paid to learn stuff they should already know but life isn't always ideal.

I'd approach it by finding a problem that's simple enough to solved relatively simple. Public variables are usually handled best by trying to find the source of a problem when you can't see what's changin gthe variables. You can design a scenario for that.

The over-inheritance may not be their fault. They may have learnt in a course designed in the 90s that's trapped in the idea that "everything must inherit". I remember the old examples of Manager extends Employee. It's just BAD. Thing is people get taught this nonsense. Still.

For C++ the Scott Meyer Effective C++ series is probably worth poniting them to (assuming they can be bothered to read something). For Java, Josh Bloch's Effective Java ("favor composition") is along the same lines. Not sure about C#.

These sorts of books give a better approach to inheritance vs composition and also give some good examples of why inheritance is (as Josh Bloch puts it) an "implementation detail". I've also heard it described as "inheritance breaks encapsulation".

I saw a good example once of inheritance vs composition with extending the capabilities of a List in Java and how inheritance required you to know implementation details of the parent to do correct whereas composition didn't. I'll see if I can find it.

cletus
I can tell you from experience that this topic wasn't broached in college, not in C++, not in Java, not in C#, not in Data Structures, not in Logic and Algorithms, and not in the senior level project. I wouldn't be surprised if it wasn't broached at this chap's college either.
George Stocker
Wow, I learnt this first year in an introductory C programming course. Coupling, cohesion, etc. C++ intro course taught abstraction, polymorphism, information hiding, etc. All first year stuff.
cletus
The topics of polymorphism, abstraction, encapsulation, inheritance were taught, no doubt about that; but actually pointing out bad code? Not so much. It was like being taught what a school was supposed to look like, but never seeing an actual foundation.
George Stocker
Got to go with Gortok on this. I went to a university well respected for its CS program, but they never touched on anything like that. (Not saying they shouldn't have...only that they didn't, and I don't think that that is uncommon.)
Beska
Beyond the introductory courses in CS, it's usually assumed that you can program. The only higher-level programming course I ever saw was the AI Programming class, which taught Lisp and Prolog.
David Thornley
Most colleges don't have a "worst practices" course, and often the entirety of the "why" is skipped in the "best practices" courses. Heck, in music theory courses they'll even miss the basic "Because it sounds terrible that way". I'd imagine Comp Sci has more problems than that.
Christopher W. Allen-Poole
Well, it's not just about testing "best/worst practices". Don't you do assignments/projects? I know if I did assignments with public variables and tight coupling I'd get marked down on it with marker comments to that effect.
cletus
+1  A: 

Ask him to make a change you know it will be hard because of his design and show him how that would happen using yours.

If he complains, tell him the truth: business will ask more bizarre changes, it's a matter of time he will see that.

+12  A: 

The problem is your expectations, not the developers lack of skill. You talk about loose coupling and information hiding as if these are simple facts or mechanical techniques - they are not. Software development is a craft and the only way to get better at a craft is to practice it and slowly and incrementally improve.

You are looking for a shortcut. You want the developer to experience an "ahah!" moment and suddenly see the wisdom in your design. I say, don't hold your breath.

Adopt the mindset of a mentor. If you want him to improve his design skills, don't "hand" him a design, let him to design it! Then review the design with him. This will give him experience, a deeper sense of ownership and more willingness to listen to your suggestions before he is knee deep in implementation.

An aside - I notice that people look for these shortcuts all the time with abstract skills but not with more "physical" skills. Take tennis for example. If you were a tennis coach and a new player kept hitting his forehands long, you wouldn't just show him a YouTube video of a Roger Federer forehand and expect him to "get it". A great forehand takes YEARS of experience as you learn the feeling and use it in different scenarios - its not your muscles learning, its your brain. It is no different with software design. You get good at it by doing it over and over again. You slowly learn from your mistakes and get better at appreciating the consequences of each individual design decision.

Mo Flanagan
+1 for the "ahah!" moment I got when reading this. It is also very true. Don't explain, let him/her experience!
eljenso
A: 

If you do Unit Testing, explain it in terms of test-writing. Alternatively, Abstract Classes and Interfaces both use loose coupling and information hiding to great effect. If you explain it to him in terms of other concepts he may already have a handle on, he'll be more likely to appreciate the concept quickly.

Jeremy DeGroot
+1  A: 

I think that OO concepts really need to be learnt practically. One really needs to do these things to understand. I go to school (engineering) and most of my peers don't really get the concept. They know in general that loose coupling is 'good' but not why. They also don't know how to achieve loose coupling. I am working on my final year project now and I got through to them by making them part of the design process. (It helped that they really did understand how and why and had an inkling of its importance)

Given your situation, here is what I would suggest:
1. Make them follow your design exactly (at least for a couple of weeks). If they want to deviate, have them discuss what and why with you. [Time constraints may not permit this].
2. Sit with them on whichever part of the design you are doing next and explain some o0f your design choices to them, with examples. Somethings that are obvious to you may need to be pointed out to them.
3. Be on the lookout for examples, both of good design and bad design and show them how that works better.

The most important task here is of delegation. You have to show them what good code looks like, maybe train them for a couple of hours. Then you agree on when to review and how you can help them (whithin your limited free time (?)) do the task well. The main thing is to get them to identify with and understand good design. Doing these things will help them 'buy-in' to the design. Once they feel it is their design, I am sure they will do better work.

Overall, I think you need to put your foot down and get them to code it right, without stifling their creativity.

I don't really have too much experience in the area. I am just giving my opinion on the subject, based on what worked for me. I hope this helps.

Note
I'd like to add that OO concepts can be learnt from books, while their application can be learnt only by practice. I have added this note in response to a comment by Christopher W. Allen-Poole.

batbrat
I'd like a caveat to your first sentence. OOP best practices has to be learned practically, but the concepts can still be learned through book-learning.
Christopher W. Allen-Poole
I just saw your comment. I totally agree. I'll add the warning!
batbrat
I wish this was really practical (that I had time and position to teach) but since they're a contractor, it won't work.
C. Ross
Ok. I sympathize with you. Sorry I couldn't be of more help.
batbrat
+6  A: 

There's nothing like a physical analogy. Walk out to your car and point out how everything complicated, hot and dangerous is pretty well isolated from the fragile human. Sit in the driver's seat and point out some of the important gauges; for example, the coolant temperature, tachometer and speedometer. Note how the gauges are remarkably similar: they all take a scalar value (from somewhere) and represent it by moving a needle to a position between min and max.

However, if you think about what's being measured, the strong motivation to maintain that isolation (aka loose coupling or information hiding) becomes a lot more obvious.

  • "How would you like to measure the coolant temperature? By looking at a gauge or by sticking your finger into near-boiling liquid?"

  • "How would you like to measure the engine rotational speed? By looking at a gauge or by letting a multi-thousand RPM crankshaft rip the flesh from your bones as you try to estimate it by hand?"

  • "How would you like to measure the car's speed? By looking at a gauge or by dragging your foot on the ground as you're roaring down the highway?"

From there, you can build on the concepts of "your coolant temperature gauge is-a gauge. It isn't-a boiling liquid" and so forth to more complicated concepts.

Bob Cross
+1  A: 

Just don't talk to him. That should teach him about information hiding. ;-)

If you did that to me, it would likely end up in someone getting punched!
Martin Brown
But you would understand information hiding... the downside is that you see it as a negative instead of a positive.
Austin Salonen
+1  A: 

I like a credit card for an example.

You have a credit card. A credit card represents your credit history. It has a balance and a APR. It has permissions and an entire financial state. It has a id, an expiration date, and a security code. The magnetic strip summarizes all of this.

When you go to your local credit-card-accepting establishment, they don't need to know that. They don't want to know that, and it is often very dangerous if they do know that. What they need to "know" is that there is a magnetic strip which will take care of all of this, and (sometimes) that the person holding the card has id to match the name printed on the card.

Giving them more information is either (in the best case) useless, or (in the worst case) dangerous. Requiring them to know which bank to check with, making sure they know how to calculate your particular APR, or allowing them to check your balance is simply silly at that point.

Christopher W. Allen-Poole
+1  A: 

If he's misinterpreting your designs, perhaps a couple pair-programming sessions will be enough to get them on track. I do have to agree with @ThomasD and will expand upon it -- the encapsulation going on here could be you. It could be a simple case of misinterpretation instead of them not understanding the concepts.

Austin Salonen
A: 

Programs are systems of interacting parts.

For a system of interacting parts to work together requires connections between these parts.

The more connections, the more costly the program.

For a fixed number of parts, a system whose parts are unnecessarily connected is more costly than a system whose parts are necessarily connected.

Unneccessary connections can only be formed in a system whose parts are unnecessarily exposed to connections from other parts.

Minimising unneccessary exposure of parts to connection from other parts is fundamental to cost-effective program development.

Loose coupling and information hiding are the fundamentals of connection-exposure minimisation.

This is not optional knowledge for a programmer.

This is fundamental.

You cannot be a cost-conscious programmer without this knowledge.

Asking how to explain loose coupling and information hiding to a new programmer is like asking how to explain surgery to a new surgeon? Or to explain architecture to a new architect? Or how to explain flying to a pilot.

If your, 'New programmers,' don't know loose coupling and information hiding, then they are not, 'New programmers;' they are potential programmers.

Curiously, it probably won't help to tell them to read the original two papers: i)Loose coupling: 'Structured design,' by W.P. Stevens, G.J. Myers and L.L. Constantine. ii)Information hiding: http://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf

A: 

Just like the move from 16 bit to 32 bit windows applications where processes were given their own address space. This stopped any other process from being able to kill your application when it "accidently" walked over your data.

Moving processes to different address spaces was like treating each process as a class, and hiding the memory internally and decoupling the processes by forcing interprocess communication to only happen via an expected interface ( eg Windows Messages ).

Stephen Bailey
+2  A: 
OscarRyz