20

I am staying in an environment, where people believe:

  1. Java generics are the feature exclusively used for library writing and not for the real coding.
  2. C++ is an OO programming language; template is an optional and avoidable feature

Though, these people rely highly on the libraries written using generic programming (e.g. STL, Java containers). If I write a code using templates or generics, the code reviewer is most likely to reject it and will comment to write it in a "proper / understandable / elegant" way.

Such mentality is applicable from normal programmer to senior most manager. There is no way out, because 90% of the time, these people have their lobbying.

What is the best way (not being cut throat) of explaining them, the practical approach of writing code which constitutes OO and generic programming both at the same time ?

yannis
  • 39,547
  • 40
  • 183
  • 216
iammilind
  • 2,232
  • 4
  • 24
  • 35
  • 11
    I wish you the best of luck, but you're probably going to have to leave if you want your way.. – The Muffin Man Oct 03 '13 at 00:28
  • 3
    @TheMuffinMan, you are right. I left that workplace and now I have my own company. Here I have complete control over the coding! – iammilind Mar 06 '14 at 02:32

9 Answers9

17

This is a specialized form of the more general question "how do you convince your superiors to start making use of a newer and better technology / way of making things?"

Unfortunately, I do not think you can, and I am not sure you should. It is by definition their choice, since they are paying you to do things in a certain way that they have chosen, not in any way you like. The best you can do is suggest that this technology is out there, lots of people are using it, and it appears to be the way of the future. You might even want to mention the fact which they of course ought to know already: that it is best for people to not let their skill set stagnate. But that's it: if they don't buy it, there is nothing you can do.

They may have other considerations which you do not have, because you are not thinking at their level. You are thinking as an engineer, they may be thinking more in business terms or even human resources terms.

  • Will generics (or whatever) improve the value of their product? Probably not.

  • Will generics (or whatever) make it harder for the people that they have already hired to do their job? Yes.

  • Will generics improve time-to-market? If the only engineer was you, maybe. But if a whole bunch of engineers need to be educated on generics before another line of code is written in the house, No.

So, you might want to consider just changing jobs. In my last job I was the first to use generics with Java, and luckily they did not have a problem with it; they expressed a concern that generics make code 'harder to read', but they let me have my way. Find a job like that.

Mike Nakis
  • 32,003
  • 7
  • 76
  • 111
15

There are still people in the world who don't use Java generics in "ordinary coding." I can believe it with C++ templates, but generics? They aren't even hard to learn/use. Seriously the best features of Java and C++ are respectively generics and templates.

The best way to convince people of things is to make a compelling argument, be non-threatening, and be right.

So long as you are not doing something like using templates as your programming language, parametric polymorphism (generics/templates) is almost certainly good.

1. Avoids code duplication.

This is obvious, but polymorphic code is general code. That is why it is called generics.

2. Supports better static checking.

Without parametric polymorphism you end up writing things like public Object clone() or public boolean equals(object b) which are not just abominations, they have types that provide no information about what they do, and invariably end up throwing exceptions all over the place. The alternative to parametric polymorphism is casts all over the place

3. Non parametric polymorphism OOP code is basically unable to handle "binary methods" in a correct way.

You use these often.

4. It is best practice

In Java, use of generics is considered best practice (see Effective Java by Josh Bloch). Major C++ thinkers like Sutter and Alexandrescu also encourage the use of templates to solve a variety of problems.

5. It fits the OO paradigm.

People often don't notice this, but the combination of sub-typing and generics produces a system MUCH more powerful expressive, and object oriented than any system with just one of them.

Consider Scala's mixins. These are a nice feature that lets you pull your objects together from component parts. Generics and templates can simulate some of these benefits. For example, say one of your objects uses a database. Good design would have you abstract out the database access into a separate class. If done right this not only lets you mock your data-store (key to testability), it also means that you can add alternative implementations like that new no-sql database. Here though, you might have a problem, mattering which implementation you use you will get different capabilities of your business object.

Generics to the rescue!

   public class Business<S extends Datastore>{
      private S store; ...
   }

Now you can start statically differentiating your Business objects based on ability to use database specific features. You still need some runtime checks and casting, but you can start building MUCH better code.

and

6. Normal code doesn't exist.

There are only three things in the programming universe:

  1. libraries,
  2. configurations, and
  3. bad code.

If you don't think about your code like it is a library you are in serious trouble when the requirements for your project change. Architecture is (arguably) the art of designing good APIs.

I find this attitude stunning. After you get used to programming with parametrized types, not using them just makes everything a pain. And, Java and C++ have a bunch of rough spots which they help remedy.

lennon310
  • 3,132
  • 6
  • 16
  • 33
Philip JF
  • 2,193
  • 14
  • 10
  • 7
    I like the notion that `normal code` doesn't exist and that there are only three kinds: `libraries`, `configurations` and `bad code`. It is an idealist reasoning though you still have to explain it to your colleagues though who might not be as idealistic as you. I do agree though that using parametrized types is simply *awesome* once you get the hang of it. – Spoike Dec 27 '11 at 10:29
  • 3
    Heck, even C++ templates aren't that hard to use if you don't use them for template metaprogramming purposes. :-) – In silico Dec 27 '11 at 18:25
  • -1 for suggesting that everyone who decides not to use generics does it just because they don't know how the feature works. – tp1 Dec 31 '11 at 11:59
  • given the potential for misuse I would say restricting/not using generics/templates can be a lot better decision that you give it credit for. – Ryathal Jan 09 '12 at 17:44
  • People who refuse to use generics/templates for large-scale software engineering will accidentally and inevitably build a "second language" - an interpreter that runs on Java, that implements whatever "business language" they have in their mind. http://en.wikipedia.org/wiki/Inner-platform_effect – rwong Jul 29 '14 at 09:27
  • Some people are wise. When they want a cup of coffee they'll make a cup of coffee. Some people are "knowledgeable". When they want a cup of coffee they'll start building a fantastic machine capable of heating, cooling, brewing, carbonating and mixing any kind of beverage; but die of thirst before it's finished. – Brendan Apr 21 '15 at 10:13
9

I would broadcast the merits of generics to the code reviewer and other colleagues ahead of any review:

1) By allowing you to specify types that are acted on by a generic class or method, the generics feature shifts the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.

2) Generics provide type safety without the overhead of multiple implementations.

So, [1] and [2] reduce the risk of error in the code. This saves the developer time and therefore the company money.

If readability is an issue then the awkwardness of using generic types could be compromised. This is one reason you might want to extend coding guidelines. This can be done in a workday context and not just for extending libraries (however, it's an idea to refactor as you go and mark possible candidate methods for libraries in the code for easy recognition later). Therefore, there would be no reason not to use them in a workaday context.

I would add a few statements about how other programmers do not have issues with generics: Generics are widely used in Java and many other languages like C#. Any serious programmer would find life difficult without such type safe building blocks.

Nonetheless, you may want to consider that some of the developers may not be up to scratch. Management could have made a conscious decision to protect projects in the past, thereby keeping these chaps out of dangerous areas. Here, both the innocent and the guilty usually get the blame as sufficient analysis or micro-management is rarely conducted.

If you put a good case forward and you are not given a reasoned response in return then secretly begin to look for another company that takes programming seriously.

Phil C
  • 1,956
  • 1
  • 18
  • 34
7

Unless you are the architect/tech lead it will be difficult to mandate that you should use generics/templates. You really should propose the generic/template solution long before the code review, preferrably before you start implementing it.

What you can do, is to demonstrate why you should use a generic in some case. If you can demonstrate the benefits, then your colleagues might agree. The possible reasons why you should use generics/templates should be the following:

  • It should let you write less code for repetetive tasks
  • It makes the programmers job easier
  • It enforces a pattern set by the solution architect
  • It encapsulates common features, that would force the programmers not to copy-paste code (i.e. avoiding the double maintenance problem)
  • It reasonably future proofs your code (though this avenue is difficult to reason about)

In a recent Java project I successfully added some generic abstract class because it satisfied some basic things: it made things easier for the others in the team, enforced the pattern that the architect already proposed and had some common code that programmers didn't need to copy and paste. It was a simple pattern that the architect wrote about that reasonably competent people still got wrong (because of the complexity of the actual system in play), but the generics marks which class goes where.

Obviously I can't show off the real example without breaching the non-disclosure agreement. But as an example of what I did would be to do the strategy pattern and enforcing it with generics. So this is the strategy pattern:

enter image description here

And in order for the programmers to enforce this pattern, you can add the generic type on Context that it should use something that has a Strategy type. Code-wise it would look something like this in Java:

// declare the generic Context class that has a type "S" 
// that is an upper bound class of Strategy
public class Context <S extends Strategy> {
    S strategy;

    // Constructor with an initial strategy
    public Context(S initialStrategy) {
        this.strategy = initialStrategy;
    }

    public void doSomething() {
      strategy.execute(); // assumes that Strategy has an execute() method.
    }

    public void setStrategy(S strategy) {
        this.strategy = strategy;
    }
}

You can do this pretty much with any pattern as far as I know. Be sure you can test your generic/template design with unit tests to see that it works, in order to have confidence in the code design.

If your colleagues don't like the idea then don't take it personally, it might not have been made as easy of a solution for them to handle as you thought. Which is why you should propose a generic/template solution before you start implementing it. You still have to work together with your colleagues to solve the actual problem in a different fashion.

Spoike
  • 14,765
  • 4
  • 43
  • 58
  • Love the diagram! Which tool did you use? – yannis Dec 27 '11 at 10:46
  • @YannisRizos I used the http://yuml.me/ that creates diagrams from text input. The beta service is a bit buggy at the moment though (you can however upload the generated picture to your post using the generated link). – Spoike Dec 27 '11 at 10:49
  • bookmarked, thanks for sharing. although I don't really want to learn yet another syntax, however simplistic, it looks cool and I'll give it a go at some point. – yannis Dec 27 '11 at 10:52
  • @YannisRizos Oh, I constantly forget the syntax myself. That's why there is [a handy samples page](http://yuml.me/diagram/scruffy/class/samples). I found it to be quicker to write simple class diagrams in yuml than to use Visio. – Spoike Dec 27 '11 at 10:54
  • @YannisRizos yUml is a cool tool. Here are a few other examples of what you can do with it: http://carnotaurus.philipcarney.com/tagged/yUML – Phil C Dec 27 '11 at 10:55
  • "We're sorry, but something went wrong." in scary red letters, is what I got following the samples page :) (the frontpage was off too, everything back to normal now). I've been using ArgoUML for far too long, something as simple as yuml is definitely welcome. I'll check it out in detail at some point - @Carnotaurus appropriate way to plug your blog, bookmarked as well :) – yannis Dec 27 '11 at 11:02
  • Ooooh, I am sooo bookmarking this! – Mike Nakis Dec 27 '11 at 12:00
  • @YannisRizos I wouldn't shamelessly plug a blog :) – Phil C Dec 27 '11 at 15:52
4

There are always several ways of doing the same thing. If your use of templates is a misuse of templates then it should fail the code review.

However, if your code fails the review, because they do not understand templates, then the problem is of different sort. In that case advise them (in a nice way) to learn templates.

BЈовић
  • 13,981
  • 8
  • 61
  • 81
4

What you're dealing with here is a collection of biases. People prefer the status quo, a groupthink has developed, and the argument has been waged a few times so that people have become entrenched in their beliefs.

One of the most effective strategies here is to focus on a tiny victory. I read the following example in a book: the author was a staunch non-Apple user. She didn't like them, and she wanted nothing to do with them. She had many discussions with people with a pro-Apple stance, and each one just pushed her heels deeper into the ground. Then someone bought her an iPod shuffle and like that, her biases disappeared. It didn't make her want to buy only Apple products, but the hard, entrenched anti-Apple stance had been replaced with a more balanced viewpoint. There was room for compromise, and she ended up slowly converting to Apple entirely.

So don't try to convince everybody all at once: it will have the opposite effect. Focus on one little thing, and the rest will happen by itself. Just get rid of the two-sided nature of the argument so that people can cross over bit by bit, instead of all at once.

The specific point to focus on depends on your situation, but here's one idea: The division you sketch between libraries and 'real code' seems very unnatural. In my view, a programmer making an application should spend 80% of his time on a library for the type of application he's making and 20% using that library to build the application. All code worth keeping should be considered a library. I would suggest to your superiors that you generalize some of your code into an in-house library (if you haven't already). By their own logic, they should use generics for this, and by the estimate above, 80% of your code can end up inside the library. Once you get everybody using generics from the other side, they should get used to it, and the biases should fade.

Peter
  • 469
  • 4
  • 9
  • Thanks Peter, it was a very insightful answer. Your thoughts apply not only for my question, but also for the general philosophy of our day to day life. – iammilind Oct 03 '13 at 05:08
2

Note "understandable". If the code reviewer does not see the benefit of generics, then all the <<<>>>-stuff is just un-understandable noise which is unnecessary.

I would suggest having a look at how many actually, current bugs (open or recently fixed) that your bug database contains that could have been avoided by using generics. Look for ClassCastExceptions.

Also note that if you do not have any bugs that could have been avoided by using generics then your colleagues have a point in that you do not need them.

2

I'd go easy on this. I moved from Java 1.4 to 1.6 a couple years back, and generics has been a real jolt. It's simple and very helpful if you are trying to juggle a few Collections, Maps and other structures. However, writing classes that take generic data as parameters, manipulate them, and pass them to other classes quickly becomes monumentally confusing. I get great satisfaction from making it all work, but wonder if the added time and effort spent was worth it. I also fear a good number of Java programmers may never really get the hang of it.

A few more random thoughts from my generic journey so far:

  • ClassCastExceptions occur at run time, but they usually appear on the first few runs and are easy to fix.
  • Every article I've read on generics states that sometimes they just don't work and you need to use @SuppressWarnings(value="unchecked") occasionally. How do you know if you are beyond the limits of generics, or if you're just being stupid and need to think harder?
  • It can be hard to apply @SuppressWarnings(value="unchecked") to just one line.
  • I added some fancy generics to one of my classes. I've known several programmers who could have enhanced the class before I genericked it who could never have touched it and gotten a clean compile afterwards.

Generics has cleaned up my code and warned me of trouble too many times for me to reject it, but I also see increased development time, extra time spent on training, and Java programmers forced off to work in C#, C, and Visual Basic...or Java 1.4. I'd focus on writing code your coworkers can understand. If you can slip in some understandable generics, great. I see Java generics as an opportunity/problem that has not yet been figured out.

RalphChapin
  • 3,270
  • 1
  • 14
  • 16
1

What needs to change is your review process. It’s not supposed to stop new things because “we’ve never done that before”. I do intentionally use new technologies so that less senior developers lean new things. (I’m very lucky having developers who are junior but very clever and not afraid of learning new things, but actually keen).

If your management is so risk-adverse and your co-developers so timid that they are afraid of anything new, that’s too bad for them. Look for a job somewhere else. I think I’m for the fourth time in my life at a point where I can say “if I knew what I learned ten years ago and nothing else I’d be useless today”. Maybe tell this to your reviewer. Maybe they are 25. If they refuse to re-learn, they’ll be useless and out of a job at 35.

gnasher729
  • 42,090
  • 4
  • 59
  • 119