9 ms·
Object Oriented Design principles Java programmers should know
- jimmaswell 14y ago.equals ()? really? why not just ==?
- jheriko 14y agoThis is worded really quite badly, but makes a good set of points.
- arethuza 14y agoShouldn't KISS (Keep It Simple Stupid) be in that list? Or at least avoiding "general-purpose tool-building factory factory" factories: http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12 http://discuss.joelonsoftware.com/default.asp?joel.3.219431....
- deleted 14y ago[deleted]
- Jenk 14y agoThe list as a whole covers KISS. Every (including those not on the list) programming principle is aimed at the end goal of keeping things simple to prevent maintenance headache.
- cturner 14y ago"Don't repeat yourself" competes with KISS. DRY creates brittle code. There's low harm in duplication of code. When something changes you don't have to refactor your class structures. You just change the code for the thing it affects. And if you have to make multiple edits it's often pretty obvious what you need to do. (Data and configuration are different, it's more important for these to have a canonical home.)
- Jenk 14y agoI strongly disagree. DRY does KISS. Much easier to maintain one instance of a function/method/block of code than multiple copy/pastes. If something requires different behaviour to what is in that extracted piece of code, then it shouldn't be using the piece of code at all. Therefore KISS and remove that reference. In conjunction with the other principles - delegate and DI/Inversion in particular - it'll be easy to substitute the delegate and minimise change.
- tinco 14y agoThe author lacks conviction: "if you use a hardcoded value more than one time consider making it public final constant" This should obviously be: "if you use a hardcoded value, make it a public final constant" And: "if you have block of code in more than two place consider making it a separate method." This should be: "if you have a block of code, consider making it a separate method" Also, half of these principles imply the other ones. edit: This is meant seriously btw, if you're giving advice to novice programmers, the instructions should be clear. If you say 'consider making a separate method' what should the programmer consider? If the programmer is new to this he or she won't know what considerations to make either. This goes for all principles by the way, they're all fine and dandy but they're also trade offs. Every time you abstract something, you risk obfuscating the code for the uninitiated. As arethuza suggests, Keep It Simple Stupid is also a solid design principle, and it contradicts a whole lot of the other principles.
- JasonFruit 14y agoI think the wishy-washy wording you see are the result of a non-native writer relying on cliches to overcome their lack of skill in English. It's easy for an unskilled person to sound arrogant or rude when they try to be firm and concise.
- keyle 14y agoI don't agree with "if you have a block of code, consider making it a separate method". I've seen it done and done it myself in the past, and it ended up being a whole lot of methods used only once and described well (by name). However it added unnecessary complexity which added to the cost of ownership of the classes. I hope someone can relate.
- konradb 14y agoI can relate - it can also be a way where you can introduce meaning to your code. As opposed to a a series of instructions without clear intention, you can put them in a function that has a name that signals your intention. So you are labelling what that code does, using language features. I'm sure there are plenty of examples of this done well and done badly.
- taeric 14y agoThere is one other "principle" that I think all programmers should keep in mind: Programs typically exist to satisfy a user's need, not provide some intrinsic code value to you.
- meaty 14y agoWhich has absolutely nothing to do with OO specifically.
- taeric 14y agoAgreed. But all too often I see people trying to adhere to some paradigms "principles," at the expense of the user value. I mean, of course you shouldn't try and deliberately flaunt any good guidelines, but the measure of your code is ultimately not these.
- meaty 14y agoI think that is implicit. The guidelines set out here allow you to deliver that value without having to rip up your product for every minor change.
- taeric 14y ago:) I can agree that it is implicit. I just want it explicit.
- w0utert 14y agoThe problem I have with lists of 'principles' like this, is that they usually carry the presumption that there are no exceptions to any one of them. IMO this is not a good way to introduce novice programmers to sound software architecture, and often leads to an unmaintainable mess of 'flexible, extensible, loosely-coupled code' that does not 'repeat itself' and 'encapsulates and abstracts away implementation details'. Especially in situations where a) none of these things actually matter, or b) most (or all) of them could have been realized with much less complexity. Just as an example, I really hate principles like 'program to interface, not implementation'. More often than not, you are not writing 'extensible frameworks' or 'reusable classes', so hiding each.and.every.class behind an interface serves no purpose. I get really depressed browsing the typical Java or C# code written by all the architecture astronauts around me that are obeying some variant of the '10 object oriented design principles' and thinking they need to make ISomething for every Something constructed by a AbstractSomethingFactory they can dream of, even though it's completely obvious only one kind Something will ever exist. TL;DR: there's almost as much risk creating crappy code blindly following what is commonly sold as 'OO design principles' as there is in hacking up everything with complete disregard of sound design and architecture. I think this should come pretty close to what your parent poster was trying to say. I also think many developers working in languages that aren't strictly OO would agree.
- mateuszf 14y agoRegarding rule "Object oriented design principle 8 – Interface Segregation principle (ISP)" ... I think this is often overused. I only introduce interfaces when there is more than one implementation. Of course if I'm designing stable API this is different. Also see: http://stackoverflow.com/a/90915/343699 http://stackoverflow.com/a/90915/343699
- mseebach 14y agoIt can, especially to novice developers, be very helpful to be forced to think of a class exclusively in terms of it's interface. Bad design seems to stand out more.
- qu4z-2 14y agoI would agree. Depending on implementation details tends to lead to much tighter coupling between components.
- deleted 14y ago[deleted]
- wheaties 14y agoSome of us working in hybrid OO-FP languages or strictly FP languages might argue against IoC. I have seen and been exposed to code bases while beautifully written are completely untraceable in cause-effect debugging. Which combination causes the error? Which config was that environment set to? Let me try to divine the structure...
- grdvnl 14y agoAgreed. There is a fine line on how much of this should be used. Teams can spend cycles trying to design everything based on IoC which might be overkill. All rules regarding keeping things simple should also apply to IoC.
- narag 14y agoI've always worked with OO, not FP. I dislike IoC for the same reasons. Also it's anti-KISS and debilitates encapsulation. The worst effect of this kind of doing things is the image of programming that it shows to beginners. Programming well has nothing to do with that, really.
- Zimahl 14y agoAgreed, I think IoC is dramatically overrated along with AoP. There are places it can be useful but it can get so complicated so quickly it actually hinders the upkeep of the application.
- grapjas 14y agoHow is any of this specific to the mess of the language that is Java?
- konradb 14y agoThis is true, it's essentially a summary of some of Clean Code by Robert Martin. Principles applicable all over the place. However to turn things a bit more constructive, let me know what languages you see as less of a mess if you have the time. It doesn't matter whether we agree and I'm not looking for a fight, just your opinion and reasoning. I might well agree.
- martinced 14y agoOh the memories. It's not very well written but most advices are sound if you're stuck in that very particular Java / C# hell. The book "Effective Java" (from 2001) still has to one the "must read" for any Java programmer that didn't read it. In it Joshua Bloch has always been very clear, from the start, about all the deeply ingrained ugly Java warts that Java had from the start (and still has). Like for example the complete and total utter impossibility to respect the equals() and hashcode() contracts in the face of inheritance. Took a long time to set in but now quite some Java programmers are beginning to accept that having equals() and hashcode() at the top of an inheritable OO hierarchy may not have been the greatest thing since sliced bread. The second book to read is Goets and al.'s "Java Concurrency in Practice" (one of the best looking programming book cover ever, which never hurts an incredibly high-quality content). But the real lesson is that: Java is too complicated and has way too many warts to ever produce beautiful code. The JVM is not all bad but "Java the language" is really fugly. Switch to a language that has a saner way to deal with concurrency (Say Clojure's STM or Go) and you can throw most of the pages in these books to the trash.
- pdog 14y agoI highly recommend the second edition of Effective Java, which is more recent (2008) and covers Java SE 5 & 6.
- lanna 14y ago"Like for example the complete and total utter impossibility to respect the equals() and hashcode() contracts in the face of inheritance." But is that a problem with Java or is it a problem with ANY OO language?
- campnic 14y agoOne additional item I would suggest is Fowler's Refactoring. In java hell, the only viable weapon is a refactoring scalpel.
- dougk16 14y agoCan you go a little more into the problems with equals() and hashCode(), or link to something? I'm by no means a hardcore Java programmer, but I've used it for several projects, and these never stood out as particularly problematic to use and override, although I kind of see how they come across as kludgy in a whitetower kind of way.
- moron4hire 14y agoI don't agree with most sentences on programming that contains the words "prevent someone from". "Classes, methods or functions should be Open for extension (new functionality) and Closed for modification. This is another beautiful object oriented design principle which prevents some-one from changing already tried and tested code." No, no, no. Let someone modify whatever the hell they want. If they screw it up, that's on them. Quit it with this childish belief that you have to control people.
- tinco 14y agoYes, but I think the closed principle is more about providing an interface, i.e.: the interface should be closed for modification so that implementing classes or interfacing services do not have to be changed everytime you add a feature. My girlfriend came up with a nice metaphor trying to follow along. The open/closed principle applies to natural language as an interface. It is important language can be extended to convey new meaning, but also important that it is closed for modification so we retain the ability to understand eachother.
- moron4hire 14y agoWith the exception of service APIs in which everyone is forced to use the latest version, I still don't agree. If we're talking about libraries, nobody is forcing people using the library to upgrade to the latest version (or at least shouldn't be). If you have a good reason to change the interface, change it, don't let the fact that it doesn't match previous versions of the interface prevent you from improving the product.
- ollysb 14y agoThe open-closed principle involves creating classes that _never_ change in the future. If you want to extend their behaviour you should subclass them. This makes some sense in a codebase with no tests, the risk of change becomes too high. But then who codes without tests these days? Given that you should always be writing tests for your code I think this principle should probably be left in the history books. It seems like a great way to add unnecessary complexity to your code base.
- oddthink 14y agoOne thing that was conspicuous for its absence was the "Law of Demeter." Is this not considered a good practice any more? It's trickier to use, because blindly applying it can lead to immense classes, but I find it a useful thing to keep in mind.
- ollysb 14y agoThe rails delegate helper really helps with this, just declare which methods you want forward, optionally with a prefix. Sometimes a different name is more descriptive but this covers a large portion of the cases. class Foo < ActiveRecord::Base belongs_to :greeter delegate :hello, :to => :greeter end
- qu4z-2 14y agoMy friend-group has taken to calling it the Sometimes Helpful Suggestion of Demeter. It's sometimes helpful, but as you say, not really a "Law".