General discussion

  • Creator
    Topic
  • #2258532

    A Blog by a mere developer.

    Locked

    by tony hopkinson ·

    blog root

All Comments

  • Author
    Replies
    • #3284367

      Is quality a casualty of doing business ?

      by tony hopkinson ·

      In reply to A Blog by a mere developer.

      Writing Quality Software Applications

      If you are in the business of writing software, either commercially or for open source. What constitutes quality ?

      • Ease of use ?
      • Applicability of the functionality ?
      • Integration, Interoperability or compatibility ?
      • Stability or robustness ?
      • Security ?
      • Speed and resource economy ?

      The split in the list was deliberate, as a developer, designer, programmer, solution provider or whatever, the lower three I can have an impact on by writing quality code. The first three are aspects of the requirement. Can I have an impact on them, well I can do what was asked properly and hope the market research boys got it right. I can point out inconsistencies, impracticalities, even impossibilities, but they should change the requirements before they change the design and implementation.

      The point I’m going to try and get across is that quality applications are much easier to achieve and far less expensive in the long run if they are made with quality code. That’s obvious you say, well you must be a quality developer. Evidence suggests it’s far from obvious to some.

      What is the first casualty in the development process when things start getting tight? Quality, poor fellow is always the first one over the top and gets scythed down by short term business imperatives or over clever technical types, every battle. Talking of war, heard the quote, “No battle plan survives contact with the enemy”, well no software survives contact with a user. They will use it in ways you never planned on, in situations you never considered, at times you’d think were insane. The one constant in life, software and the universe is change.

      Hence the critical factor missing off the above list -:, Quality sofware can be adapted.
      It must be, it’s never finished, a release is simply a hopefully working subset of a range of functionality that might be required, by someone, sometime.

      Interfaces can be enhanced, even added. Resources can be pooled, expensive routines can be optimised, security can be added, stability improved, features enhanced or added, integration broadened or made deeper. When are at least some of these, not desirable features of an application ? When can’t they be marketed, when can they not be profited from ?

      So, the business point made, though not necessarily proven, what is the key component of a quality application that a devloper can impact, Quality code. Not an upgraded OS, not better hardware, not killing competition so you don’t have to bother, not constraining functionality so it doesn’t matter, not even quality developers. These are all short term measures, every one of them is guaranteed not to last, because change is a given and they are all enviromental.

      • OS’s are software, subject to exactly the same problems as applications, though to a much greater degree.
      • Hardware always becomes obsolete.
      • Corner the market, you just give someone a more lucrative target to aim at.
      • Throw quality in the bin and you give them an easier target as well.
      • Throw functionality in the bin, you won’t hit the target, become obsolete before you put the lid back on the rubbish receptacle.
      • Quality developers, well they get moved into management, their skillsets become obsolete, they leave to work for someone who told them quality IS important, they leave and then charge you an arm and a leg for their services, they retire, they switch to flipping burgers because they are only glorified clerks after all.

      Quality code though, lasts. It can survive anything short of a nuclear explosion, even that if your offsite back up is very remote. If it’s the real driver, it can even survive low quality developers, even better, make them into higher quality developers.

      How many times has this happened. We’d like to add feature X to software Y. X is a natural extension to Y, it’s very similar from the outside, should be simple. The response, well we could give you a bit of X sometimes, if you don’t mind having Z, in a month, or you are looking at a total rewrite and next year.

      Now this could be for several reasons, but in my experience, most of the time it’s because the code base is of a low quality, more commonly known as, crap.
      How did it get to be crap ? Well it either started as crap, or cpl Quality got shot down too many times in a row. More generally the latter.
      After all the ‘easiest’ way to deal with a code base that is hard (expensive) to change is to bodge, patch, snowball, spaghetti and poorly interface to other crap. It’s probably a total co-incidence but all these ‘ah’ procedures actually result in an even lower quality code that’s even harder to change.
      Guess we must be doing something wrong huh ?

      This is not a diatribe against those stupid business types who don’t understand technology. Of course they don’t, that’s what we are there for. Some might, some could, some do, but it’s not their job, it’s ours. They aren’t stupid, they just aren’t technical. Well OK some do appear to be stupid, but I’ve met as many stupid techs as I have business types.

      Now some of our problems are down to communication failures, either we didn’t explain, didn’t explain correctly or just as bad didn’t make sure we had been understood. Sometimes business types will simply stumble over technical hurdles in order to hit the finishing tape. Like when something has already been promised, what was promised was changed by someone important, an unfortunate error in the costing, a massive change in the business environment and the oft quoted “What do you know you are a mere tech”.

      There are a whole raft of other reasons for a low quality code base though, ones that over a product or even a version lifetime our non-technical colleagues would judge themselves benefitted by. These things are generally so basic, it makes you want to cry at their absence. The only reason we don’t, is because we are so badly dehydrated.

      How do you write code that you can change with relative ease?

      You write code that you can read with relative ease.

      You write code that “does what it says on the tin”.

      Annotation, naming conventions, function length, prettification styles, calling conventions, coding standards, documentation, continuity, all things that help you read what is already there.

      If you can’t read a piece of code , you can’t understand it.
      If you can’t understand it, you dare not change it.
      If you daren’t change it and you can’t afford to rewrite it, then you bodge, patch, snowball, spaghetti, screw up or otherwise fail.

      A higher quality, less expensive bodge is not what we are meant to be about!

      If you see a piece of readable code that suits your needs, does only what it says and you understand how it works, you are going to re-use it. 99% of business coding is plagiarism after all. Why would you write something that you’ll have to prove works, when you already have something that is proven to work?.

      If you have to add an other routine to do something similar, you aren’t going to invent a new way of doing it, you’ll cut and paste, have a wee twiddle and be more confident about what you’ve done.
      Not only is the end result of a higher quality, it’s quicker to produce !. It’s cheaper, it gives you more time on the harder bits. It’s easier to test, it’s less likely to have a coding bug, it’s more stable, it’s more rewarding.

      Why aren’t we bloody doing it then ?

      Oh yes I include myself, for one reason or another I’ve put my name to as many bodges as you buggers.

      We are not talking rocket science here, not fuzzy neural network self programming AIs. We are talking invoice total, print, save, export to csv. Basic building blocks for an application, if you build a house with crap bricks, you get a crap house. A house is a very complex piece of engineering built out of extremely simple (at some perspective) bits of engineering. Programming is not dropping a button on a form in an IDE, it’s not agile, it’s not UML, it’s not C#, Pascal or any other language. It’s taking a complex requirement and breaking it up into easy to understand bits !

      How can it be easy to understand, if you can’t bloody read it ?

      My favourite example

      int function IsNotBanded(int ProductID);
      {
         prodStruct prod;  // Product to be tallied
      
         If (GetProduct(ProductID))
      {
      If (Prod.NotBanded != 'N' ) // test the tally flag return TRUE else return FALSE; } } ..... If !IsNotBanded ....Argghhhh !!!

      If you are confused by the references to tally, well it’s because some lackwit cut and pasted this routine from a similar one, IsTallied !

      Also Getproduct can only succeed, because otherwise calling the function would be daft wouldn’t it.

      This will seem strange but in the next version, someone misinterpreted this code resulting in several productions delays running in to ?1000s in lost profit.

      The input screen where the flag was set was as follows

      Banded – X (Y/N)

      Can’t imagine how the confusion arose, I mean everyone would do it like this would n’t they ?

      No it wasn’t me, I did the spectacular bodge that fixed the fault, we were losing our production bonus! It was still there six years later when we rewrote, not after though.

      Glossary of terms

      • Bodge – a permanently temporary fix to a bug.
      • Code base – the source for all your applications, be it VBScript or C
      • Crap – excrement
      • Low Quality – cheap ass crap
      • Patch – a temporarily permanent fix to a bug
      • Quality – A once rare animal, now extinct. Though there have been unsubstantiated claims of it’s continued existance by various software producers. These are immediately recognisable, they have smarmy grins, bulging wallets and their hands outstretched for more.
      • Total rewrite – the far too expensive alternative to the existing crap.
      • Snowball – Roll a ball of bad code in some good code resulting in a larger ball of bad code.
      • Screw up – a failure to notice that this once crap code is called by another piece of crap code, that relied on how crap it was.
      • Spaghetti – get some bad code to call some more bad code resulting in the right answer this once and at least two wrong answers next time.
      • #3198986

        Is quality a casualty of doing business ?

        by justin james ·

        In reply to Is quality a casualty of doing business ?

        Tony –

        Good post. I love that code example. The very first mistake the writer made was calling it “IsNotBanded”. “IsBanded” is a much simpler method to be dealing with; I try my best to never write negatives into my Booleans, because code that is filled with double negatives is impossible to maintain. !IsNotBanded indeed…

        To quote the film Under Seige: “… coming up with last minute solutions to impossible problems that someone else created.” This is a great description of most of the projects that I get to work on. Architecting a solution? Who has time for that when you’re given a 2 day deadline? Interoperability, testing, exception handling, validation, optimization? Sorry, the customer forgot to ask us to do the project until 5 days into a 7 day deadline. Managers also seem to treat coders as multicore CPUs. They think that we can just run our little development process, and the moment something blocks progress, instantly switch to another project and back to the original as soon as that thread wakes up again. It does not work like that. When I am in the middle of working, there are huge costs for context switching. If I have to wait three days to get the specifications for data validation from the business analysts, it is not like I can just pick up where I left off without having to review where I was…

        Quality code is far too often sacrificed on the altar of deadlines. This is an age old, unresolvable problem. When coders drive the development cycle, it won’t get finished soon enough to help the business. When business drives the cycle, the deadlines are impossible to meet. such is life. 🙂

        J.Ja

      • #3284202

        Is quality a casualty of doing business ?

        by tony hopkinson ·

        In reply to Is quality a casualty of doing business ?

        That was the point that I wanted to gloss over, I couldn’t leave it out we all know it’s true. But a lot of the time we aren’t helping ourselves. Ok you’ve got to implement a poor design, doesn’t mean you have to implement it poorly though does it ?

        Thanks for the comment anyway, I thought I was talking to myself again for a minute.
        LOL

        Next one, is going to my idea of readable code, which of course isn’t going to be anybody elses.

      • #3284109

        Is quality a casualty of doing business ?

        by justin james ·

        In reply to Is quality a casualty of doing business ?

        From what I can tell, you & I may not write readable code the same way, but both you & I would be able to read each other’s code very well. In my most recent blogs, there is a lot of code going up.

        I tend to be extremely verbose with function/method and variable/property names (bytes for source code are cheap, debugging time is not), but I am a big stickler for code that anyone who understands the basics of programming should be able to follow.

        J.Ja

      • #3230688

        Is quality a casualty of doing business ?

        by hubert1497 ·

        In reply to Is quality a casualty of doing business ?

        A college instructor of mine used to teach (preach?) that NOT logic was just that – Not Logic. Toss in that the NOT might require you to also reverse certain AND’s & OR’s and you’ve got a real nightmare on your hands. With the exception of straightforward tests such as != 0, or NOT .EOF, NOT logic can generally be restructured to be more readable (and maintainable).

        “Back in the day” software used to have a lifespan of 10-15 years and it was estimated that at least 50% of your IT budget would be in supporting (not designing / developing) the software. Nowadays software has a lifespan of 2 years so many times the attitude is: “Why spend the time to write it eloquently? It’ll be obsolete 2 months after it’s implemented.” If you’re Management, or taught yourself to code in your bedroom at age 12 and never sought any subsequent formal training, I suppose it’s understandable how you could arrive at that conclusion. But if you’re a “professional” (in the true sense of the word), you can probably design & develop quality code just as quickly as someone throwing crap together. Or at least recognize when you’ve developed crap.

        And being an old fart my definition of spaghetti is slightly different than yours. “Spaghetti Code” referred to code with so many GOTO’s that if flowcharted out the resulting connecting lines would resemble a bowl of spaghetti. But, the output of this type of code would generally result in your definition, so yours also fits well.

        As for the unrealistic deadlines Justin mentioned, I think the media (movies, TV) is partly to blame. We watch some kid write a world-saving program in 30-60 minutes (minus commercials) and the uninformed / uneducated come away brainwashed, believing that’s all the time it should take. But I guess watching a show about Analysis, Design, Testing, and Documentation would be pretty boring.

        Finally, I’ll leave you with a quote from Robert Pirsig’s book: ‘Zen and the Art of Motorcycle Maintenance’: “Man does not define Quality. A man’s choice of ‘quality’ defines the man.”

      • #3230627

        Is quality a casualty of doing business ?

        by snoopdoug ·

        In reply to Is quality a casualty of doing business ?

        First we must define the term “quality”. Good luck. Philosophy has struggled with the term “good” since Plato mused over it ~400BC.

        From a customer’s standpoint quality means applicability, robustness, fit and finish.

        From a manager’s perspective quality means feature set, timely delivery, marketability.

        From a developer’s view quality means readable/maintainable code, appropriately named variables and methods, straightforward algorithms, no magic numbers.

        So how can we agree on quality?

        I think the problem lies in the malleability of software. Just because we can change the code base so easily and rapidly does not mean we should. Who ever heard of a bridge project that decided to switch from concrete to steel half way across the river? Or from pier blocks to suspension? Yet we hear all the time of folks who expect to “just plug in SQL server instead of Oracle” like it’s flipping a light switch (leaving aside the argument that any connection to an external system should be an interface, you still have to implement the class).

        We are our own worst enemy. I’ve sat in meetings where senior staff demanded we work night and day until some new functionality got implemented. I don’t recall them demanding the sales staff pound the pavement until $10 million in sales hit the books, do you? Why pick on development this way? Because we deliver without complaint.

        Boo-hoo, the big, bad management made me work all weekend. Show some backbone. Tell them NO. Or do the classic passive-aggressive technique of acceding to their demands, then write the hacky/crappy code we all love to maintain.

        Reminds me of my hardware days: cheaper, faster, smaller–pick any two. In software it’s features, delivery date, quality.

        doug

      • #3230445

        Is quality a casualty of doing business ?

        by bobmccarty ·

        In reply to Is quality a casualty of doing business ?

        All so true.  I’ve experienced the same frustrations. 

        I would also say that it’s not just the business types or the former developers turned managers who are the enemies of quality.  Most developers don’t understand or at least do not value the concepts you mention.  Very experienced developers can deliver code, eventually, that is devoid of the type of quality you discuss and still meets the stated requirements.  So, there is little peer support in addition to no management support. 

        I think the path out (not really a path, just a compass direction to take though the jungle) is to convince management by demonstrating to management the fact that quality will not just help the next release (that’s a non-starter) but that quality will greatly increase the chances of meeting this release’s goals, very much including schedule goals.  It’s a difficult trek even with a good compass. 

      • #3200674

        Is quality a casualty of doing business ?

        by tony hopkinson ·

        In reply to Is quality a casualty of doing business ?

        Thanks for all your comments.

        I’m an old fart as well, my definition of spaghetti got modified after seeing the same result with no GOTOs. May be we should call it ravioli,  a sort of blocky pasta.

        There are a lot of pressures of devlopers nowadays, we do have the power to reduce some of it though and we don’t.

        As I hoped to get across most of it is basic stuff, styles will differ and they can be a readability problem, but a prettifier will sort that out. There’s no excuse for lazy mistakes though, they take just as long to make as it doing right in the first place, and that’s without having to go back to the code, which of course you nearly always do.

        Management aren’t going to listen to reasons why we couldn’t be bothered to use a long variable name and then misinterpreted it later. To be quite honest nor am I.

        Not even long and short.

        Are AdjPrft and AdjProfit the same thing, if so why have they got different names, if not  why have the got similar names. Wading though other peoples code, under pressure, not too sure of the environment because you are new, you don’t need crap like that.

        Real example, one was an adjustment to the profit, the other was the profit after adjustments. Two very different fellas.

         

      • #3200345

        Is quality a casualty of doing business ?

        by wayne m. ·

        In reply to Is quality a casualty of doing business ?

        Hi Tony,

        I think we are very much in agreement here, though I would like to throw out some additional ideas for consideration.

        1) Software quality is actually a composite of software qualities.  Each software quality has a variable measure and will never be completely met.  One must take care when addressing software quality as a whole and not focus on one individual quality to the exclusion of the others.  (Okay, that is a very confusing statement.  Just think software “qualities” and I think it will be clear).

        2) Refactoring is a necessary process to improving code readability and minimizing maintence cost and effort.  The IsNotBanded() example above seems to be a candidate for refactoring.  I doubt we will ever understand why the wirter chose this particular name and implementation.  What we can do is make sure our development processes do not prevent correction and ensure that they actively encourage it.

        3) Too many current software development processes assume that developers will do a (very) poor job and try to externally force quality on to them.  This approach creates the feeling that software quantity can be maintained, but software quality may be sacrificed to time pressures.  If, however, we take the approach that software quality is inherent in the processes used by the developers, then software quality becomes fixed (or slowly improving) and software quantity may be sacrificed to time pressures.

        Software quality is an important topic for discussion.  Thanks for bringing it up, Tony!

         

      • #3228362

        Is quality a casualty of doing business ?

        by tony hopkinson ·

        In reply to Is quality a casualty of doing business ?

        Point 3 is the topic of my next blog

        I came out of manufacturing. There quality and and quality control are split. One should be inherrent to the process the other,  some form of measure to see if it still is.

        Refactoring should also be part of the quality process. However like sensible standards et al. it is very difficult if not impossible to introduce to a large and already messed up code base. At the point you are really shifting to an incremental rewrite. Those are damn expensive, if you’ve got a lot of interdependancies fraught with risk as well. As soon as you get there, a full no holds barred start again rewrite starts to look more cost effective. So you end up sticking the current codebase in maintenance mode and doing it over. Not a new idea, whats annoying me is over twenty years I keep ending up coming to a new place and shouting rewrite at the top of my voice until someone says I think he’s right you know.

        I got what you meant all designs are a compromise, we just need to stop permanently compromising the design.

      • #3226626

        Is quality a casualty of doing business ?

        by reiki33 ·

        In reply to Is quality a casualty of doing business ?

        One of the things I learned in college on a project, oh, so many years ago, is that if a user has an input field, over the life of a product, every possible input will be tried.  I seem to have the ability to perform this testing function on my own code.  

        One project required a “small” accounting function.  I told the project manager it would take 3 months.  That includes documentation, full testing, and “productizing” it.  He promised the customer it would be ready in 1 month.  We differed.  As project manager, he won.  The piece with which my code interfaced was really in the same position.  My compatriot delivered his code in the projected 1 month.  I delivered mine in the promised 3 months and was reprimanded for being late, although it was on time with my projection.  After the third month, my compatriot was still trying to get his stuff to work.  There was only one reported complaint about my code after I left the project.  It took time, but I was finally able to demonstrate the incorrect value I returned resulted from a bad value returned from a method call into an object built by my compatriot!  Now, granted, I was able to isolate my code with a well defined interface.  Since no one understood the accounting side of things, this was necessary.  It may also be evident that the other side of the interface had moving and slippery specifications.  

        One nice comment came out of a layered product I built using the UniVerse database transaction logs to replicate the data to a remote server, either for disaster recovery or use as a reporting server.  Our software engineers have been tasked to integrate my functionality into the base product.  “TLR source code files are very clean,
        written in good style and easy to read.  In Mark Baldridge?s UniVerse Transaction Log Replication document, all the details of subsystem are documented including the line by line comments for each configuration parameters.”  Pret-ty scar-ry; yes?

      • #3203463

        Is quality a casualty of doing business ?

        by tony hopkinson ·

        In reply to Is quality a casualty of doing business ?

        Sacrificing quality to make deadlines always misses deadlines. Sacrifice function before quality. This can’t be stressed enough, low quality code costs more and achieves less.

        I  had to mention the PM issues in any discussion of softare quality, but I wanted to concentrate more on what we can affect, than what we just have to live with because projects overlap period end financial reports.

        Pointy headed managers and Mr Magoo bean counters are the crosses we have to bear for actually daring to enjoy what we do and expecting to be payed for it.

        Line by line comments. Oh yeah great idea ,double your maintenance overhead on any change, makes sense to me.
        Another wonderful disconnect with reality from academia.

    • #3227034

      A 100% foolproof way of writing quality code Part I

      by tony hopkinson ·

      In reply to A Blog by a mere developer.

      Only kidding, apparently TR are thinking about paying bloggers based on hits. I was just practicing, a title like that should get hit often. The idiot who wrote it, even more often.

      So calm down. For those who didn’t read my blog “Is Quality a Casualty of doing Business?”, Why Not ? Summarised it basically put forward the idea that quality software is more likely to come from quality code. When I’m talking quality, I’m not talking about the time honoured marketing measures, but underlying factors, essentially cost of change.

      Any short cut around quality will cost you later, it could cost you now if you are a part of a team. On top of that it makes us look like clowns. Delaying a release date by two weeks because someone misintrepreted what i was, is not going to
      make you look good and I guarantee the pressure put on you by the business will not be an acceptable excuse. If you were buying your own code, you wouldn’t accept that from yourself would you?

      What does quality cost ? If your developers have bought into it and police themselves, nothing, in fact cost of development will reduce. If you have to set up external policing, then you’ve got to pay someone to do it, but once you’ve got a quality foundation, it’s easier for developers to continue with it than not, so how much you benefit, will depend on how effectively you police. As pointed out though in response to my last article the external imposition of standards rarely works Thankyou Wayne. This article is about why.

      One of the things you have to remember about code quality standards is they were developed when a lot of the mechanisms forwriting quality code were not available. When you couldn’t have long names, when the number of types of variable were much more limited, when compilers were much slower and syntax far simpler, when memory and disk space was at a premium. Most of us operate in much more intelligent environments now, so we need to start being more intelligent in our quality practices as well.

      So given my argument that readability is the foundation of quality. What is readable code? Obviously there can’t be a
      quantitative definition, even some of the obvious things you should do, need to be qualified. Meaningful variable names for instance. There’s a lot of jargon involved. I worked in the steel industry, there’s a product called a bloom, without the context even I may hesitate to say the code didn’t have something to do with flowers. That’s probably an easy one, but order or invoice? Is this sales or purchase?

      Quality Standard Number 1 Don’t assume people know what you are talking about.

      Right let’s talk about a standard, we’ve all seen, shook our heads over and then completely ignored. You will indent by three spaces. It could have been two spaces, three tabs, half a page or 14 pixels. That doesn’t matter. In some respects not even ‘You will indent’ matters. There are very few of us who don’t indent, you might as well have said “You will breathe while coding”. Indentation style is quality nuetral, and a habit developed very early on. I indent by two spaces, I’ve been doing it for twenty years. To be quite honest if it doesn’t suit you, who cares? Load up a prettifier, and change my indentation style to the one you are comfortable with.

      Next stupid standard. You will line up the brackets in a compound statement like so.


      If (Condition) Then
      Begin
      // insert code here
      End;

      This is the way I’ve been doing it for twenty years, so it must be right eh? Many people have been doing it just as long in a different but an equally acceptable way. The prettifier will sort this out, in fact this is why I consider how you indent depracated. How you indent and what you indent being an ingrained habit that can easily be coped with. Getting a developer to change their style in these respects will cost you far more than the seconds it takes to change a style
      with a prettifier. Worse still it obscures important issues.

      Quality Standard Number 2 We expect finished code to be in this style when it’s accepted into the code base.

      Third stupid standard. You will comment everything.
      I have a love hate relationship with annotation. A good comment can save you hours or even days of work, a bad or missing one can cost you the same. The idea that if you comment everything you will never miss one and the practice means you never do a bad one, is far from accurate in my opinion. I’ve seen coders spending time trying to come up with a comment that wasn’t merely a translation into english of the code. Worse still if they succeeded, all they achieved was confusing the reader of it.

      int i; // the invoice number
      int invoicenumber; // the number of the invoice
      int invoicenumber; // the number of the order
      int invoicenumber;

      Option 1, what are you coding in ?. This was completely necessary way back when, if you are still in an environment where you can’t have long variable names, comment away, you will be thanked!

      Option 2, so you think I’m stupid? Comments should add to code, if they don’t, don’t add them. Spurious comments are a waste of everything.

      Option 3, illustrates a long standing problem with the overly verbose. Cut and paste. Whoever is reading your code has now lost all confidence in you. They think you are a complete twonk and won’t trust your comments, logic or naming.

      Option 4, my choice unsurprisingly enough. No comment required,what you might call self documenting code. I have a simple rationale for comments. Every comment can be viewed as failure to write readable code. If it is a failure, stop commenting and address the real problem. If you see an inline comment in my code, I guarantee, it will be current, correct and a must read.

      I should make it clear that I distinguish between annotation comments and documentation comments. Though I’ll do everything in my meagre power to obviate the need for either. A lot of standards request a bit of a description for a routine after the header. Personally I’m not positive that LoadInvoicesByCustomer needs a bit of text that says . This function will load the invoices for a customer. Author and date written could be useful. The fact that the routine expects customerid to be valid could be very useful, though we’ll get round to that in my quality design discusion.

      Inline comments should be used as infrequently as possible. They turn up in searches, they are high maintenance and they distract from the code.

      Quality Standard Number 3 Any comments will add to readability.

      The first quality standard in the usual list that I do like, functions should be about a page of text maximum. This actually runs smack into design issues, but in terms of simple readability of code the more operations something carries out the harder it is to hold the concept in your head.

      Being an old fart, probably the first structured design methodology I remember, is top down. For the younger reader it wasvery simple, though you do have to remember it was invented when processing was much more linear. It loses some of it’s utility in an event driven environment, but there is one concept from it that definitely carried over.


      1 Initialise
      1.1 Set Up Session
      1.2 reset flags
      1.3 Read Customer File
      2 Collect Data
      2.1 Display Customer File
      2.2 Geta customer selection
      3 Process Data
      3.1 Load Invoices for selected customer
      3.2 Print Invoices for selected customer
      3.3 Mark Invoices as printed
      4 Output result of Processing
      4.1 Output printing confirmation for customer
      4.2 Summarise processing, count and value of invoices

      The valuable concept is the levels. My argument is that at each level the function is effectively atomic, it does one thing. The routine Initialise, initialises. At this, the top level, this is the only thing you need to know about it. So I keep adding functions that atomicise the requirement.

      Quality Standard Number 4 Try to make all functions atomic at each level of detail.

      My next point I wish to illustrate with a few examples


      int invoicenumber, ordernumber,customernumber;

      A lot of the time the first change to this code will be to break this statement up when you find ordernumber is in fact alphanumeric. Even worse as my usual language of choice is pascal based.

      invoicenumber, ordernumber,customernumber : integer;

      Cast your eye over it , you have to track to the end of the line to find out what type it is. I do like to use white space to make my declarations tabular.

      x := 10; y := 15 ; z := 10; x := x / (y / z); y := y / (x / z);

      Now seeing as x, y and z are standard variable names in 3D graphics, I won’t shoot you for that. Put a load of separate statements on one line, though invest in kevlar before we meet.

      If (x = 0) Then y := 10 else y := 20;

      Where’s my gun!. I work within an IDE, how do I put a debug mark on one of the conditions. Not to mention if you mix this with standard indented layout, the indentations look wrong.

      x := ((b * -1) + (b*b) + (4 * a * c)) / (2 * a);

      Now this one isn’t too bad, it’s obviously a solution for one root of a quadratic equation! Also breaking it up into bits, coming up with a useful name for the intermediate products would be taxing. On top of that no use has been made of operator precedence to remove parentheses.

      x := a * b + c;

      Now I know that * has a higher precedence than +, writing your code to rely on this though, makes it fragile and less portable. All compilers agree that parentheses are in charge, you can’t go wrong with them. Well you can, if you get an expression that can be broken into understandable chunks, do so.

      Another compiler specific piece of confusion.

      If (x = 0 ) Then
      If (y = 0) Then
      z := 0
      Else
      z := x * y;

      Which if does the else correspond to ?
      Which one did you mean it to correspond to ?
      I will put you up in front of a firing squad for this one, it’s plain lazy.

      A more contentious point, the with statement. In some ways with adds to readability, it does however cause problems with debugging in IDEs and it can definitely make changing the code a real pain.I do not use it. I can live with it though. With two famous exceptions which I’ve never seen justified. Compound and nested withs. I see either of these, you will shoot yourself in preference to the cruel revenge I will wreak on your person.I’ve never seen a faster way to go wrong than this, except making all your variables global. That I will cover in the article on design though. Rest assured I will not be recommending their use.

      Just as an aside when I could do with with but I’d rather be without it. Here’s a common situation.


      MyObjectList.Items[Index].AnObject.Property1 := 10;
      MyObjectList.Items[Index].AnObject.Property2 := True;
      MyObjectList.Items[Index].AnObject.Property3 := 10.167;
      MyObjectList.Items[Index].AnObject.Property4 := 'Ughh';

      Now I don’t find this too unreadable if everything stays on one line and fits on the screen. If it does start overflowing though, it becomes a mess. My simple non with solution would be.


      MyObject := MyObjectList.Items[Index].AnObject;
      MyObject.Property1 := 10;
      MyObject.Property2 := True;
      MyObject.Property3 := 10.167;
      MyObject.Property4 := 'Ughh';

      Quality Standard Number 5 Terseness is not a requirement.

      Stolen from the definition of xml, this one. Note this is particularly relevant to compiled environments, even tokenised ones such as java byte code. In scripting where the raw source is parsed. Parsing costs time and may impact performance. Though why anyone would choose to use a scripting language where this could be a factor is completely beyond me.

      The last point I want to finish one in terms of style is naming. You’ll often see in a list of standards. You will use hungarian notation. Like comments I feel this is overused, to the point where it’s value is diminished. Secondly when our hungarian colleague came out with this, things were far simpler. Even without objects, api structures, common intelligent entities such as GUIDs, IPs, etc the muliplicity of available types soon exhausts everybody’s patience.What does strSurname tell you? Surname is a string? What the heck else would it be? On top of that what sort of string? pchar, ansi, wide, bstr, short …

      I do use hungarian notation, when it adds to readability. strBeginDate for instance. At the point I know it is a str I can come up with the relevant function or operator for it. If it was called BeginDate though, I would n’t be looking at string functions at all. For those of you who think variants are the way round this, expect to get yourself a new one ripped in my design article.

      Another one you see is Procedures that do things should be verbs. In essence I agree, but with one proviso. If you need a thesaurus to come up with another name to differentiate the action this function takes as compared to that one because it does the action in a slightly different way, you have gone wrong.

      Choose to use retrieve, load or get or fetch or whatever and stick to it. Do not use Load if it’s from file, fetch from a database etc. What you have just done there is effectively exposed an implementation detail, something our teachers spent days drumming into us not to do. Worse still, change the implementation without changing this oh so clever name and from then on, it will be an utter and complete waste of time. As soon as the person reading the code susses out you haven’t been consistent about it, they have to examine the detail of the function.

      Quality Standard Number 6 You will use a consistent naming strategy.

      This is probably the most difficult and most critical readability policy you can implement. Back in the old days, there used to be a thing called a data dictionary. In a good project this was a deliverable. The analysts would kick it off with definitions gleaned from requirements. These would often be jargon specific to the clients’s environment. The analysts would explain the concept. These names were generally a good start for the UI as well. Right at the start I mentioned the steel product Bloom. Everyone in the industry knows what a bloom is, very few outside do. Calling it a big lump of metal, might be accurate, but will confuse the heck out of your client. Other big lumps of metal are pigs, ingots, billets, sections, coils…

      Along comes the designer or architect and he’ll invent some implementation terms add them in and then map them to the customer term. Eventually when you got down to coding, this is in the old days where basically coding was a translation task, anything important was already named.

      This came out of the old waterfall or V lifecycle which has fallen into disrepute for well documented reasons in many projects. However I feel the data dictionary is a baby we threw out with the bathwater. We should nip outside, catch it and have a fresh look. You’d build it more incrementally and it would exist in a less than consistent state until the end of the project. But if used as a communal resource, your names would be as consistent as the dictionary itself and it is far easier to police.

      Once in place it becomes pervasive.

      • Analysts will use it to define requirements.
      • Developers will use the same term as the analyst which is the same term as the client.
      • New additions to the team can use it instead of making assumptions based on past contexts.
      • It’s a very effective piece of documentation all by itself.
      • Your technical authors will love it.
      • It’s a jargon buster.
      • Include data type, ranges, you’ve got a lot of simple validations defined.
      • Cross reference it and you avoid two different names for the same thing, or the same name for two different things.

      One other contentious issue it will sort out, are we using OrderNumber, orderNumber, ordernumber, order_number,
      Order_number…..

      Pick a standard, define it, and stick to it. It make take a while but it will become second nature. With an external list of terms, you even have a hope of tidying up after developers who struggled to switch to the ‘new’ convention.

      Well that’s as much as I could think of in terms of quality and style that does not relate directly to design. That will be the topic of my next article.

      As always, all comments appreciated as long as they aren’t spurious or misleading.

      • #3204918

        A 100% foolproof way of writing quality code Part I

        by wayne m. ·

        In reply to A 100% foolproof way of writing quality code Part I

        Hi Tony, it looks like we are thinking along the same lines.  I have long felt that most coding standards emphasized style issues over readability issues.  Once I put my own ego in check, I realized that I was able to read code with multiple indentation  lengths, brace placements, and combinations of camel case and underscores in names equally well.  I also realized that none of these issues were leading to any of the code bugs that I needed to resolve.  Here is my own list of coding standards plus an extension of your Quality Standard 4.

        1) Code should read like text not mathematics.

        2) Names should be based on function not data structure.

        3) Don’t use cute names.  Avoid license plate / text messaging abbreviations.

        4) Should use subroutines, functions, or methods in place of block level comments or indentation levels greater than one.

        5) Specify level of code clean up a reader can do without asking.  There will always code that is less than perfect.  Expect developers to clean it up when they find it, but set limits as well.

        6) As an extension of “Try to make all functions atomic …”, replace sequential property set operations with a single, multiparameter set method.

        I like to keep things short, because if someone understands the statement, then he doesn’t need the detail, and if someone doesn’t understand the statement, then he is much more likely to accept it if he asks or tries to puzzled it out himself.

         

      • #3203069

        A 100% foolproof way of writing quality code Part I

        by tony hopkinson ·

        In reply to A 100% foolproof way of writing quality code Part I

        Multiple parameters, not on of my favourites that.

        I’ve somtims made code more readable by passing in a list of properties (Name = value). You can access by a hash of the property name or iterate as well, though you’ve got to accept them performance hit, though most times that’s negligible.

        I might cover that off in design, intutive approach or something

        I don’t like thumping great signatures nd then sopending 80% of teh function figuring out what was was being requested.  It can work, it can fail, which i why nithr of us would com out with the you must do this crap, that is so popular in coding standards.

         

         

      • #3226447

        A 100% foolproof way of writing quality code Part I

        by wayne m. ·

        In reply to A 100% foolproof way of writing quality code Part I

        Yeah, thats one of the reasons I’m not a big fan of coding standard commandments.  I took me a long time to realize it, but there are multiple approaches to any problem and rarely is any specific approach fatal.

        I still enjoy debating the absolute right way to write code, as long as everyone understands not to take it seriously.

        – Wayne

         

      • #3205293

        A 100% foolproof way of writing quality code Part I

        by jim-mn ·

        In reply to A 100% foolproof way of writing quality code Part I

        Thanks for taking the time to share your impressions of important coding practices. However, I wish you would proofread a bit more carefully. Perhaps have someone else do it; as you know, it’s hard to put ourselves in the frame of mind of someone reading our writing to learn what we have to say. Doing only that (not actually trying to improve it) I found about 20 errors on first read. Yes, I know it’s a “blog”, but you also call it an “article”.

        But most of all, please lose the violence and weaponry. Reading about your ripping my flesh in a sensitive and valuable part of my anatomy is unpleasant, distracting,?and not at all helpful or?funny, and I’m not interested in meeting anyone for which the encounter might indicate the need for kevlar. A simple, objective rating of the seriousness of the error being discussed would be much more informative and improve the tone from immature and combative to adult and nourishing.

        If you agree, it would be nice to have _all_ of the “Parts” / articles in your series in the same, helpful style, so I hope you edit this first one also.

      • #3205267

        A 100% foolproof way of writing quality code Part I

        by bob135 ·

        In reply to A 100% foolproof way of writing quality code Part I

        One issue I have with spacing (you use 2 spaces): When you open source code files that mix indentation using spaces and indentation using tabs, you end up with absolutely nothing that lines up. Some lines are way off to the right of the editor. You say to just run the code through a formatter. We can’t always do that because of version control and diffs. If we run code through a formatter, merging is more of a pain. Also, in some CM systems, we submit a diff line of code count (worthless metrics, but required by customer and management). Formatting code really throws this off. One other issue is that if I format code written by somebody else, they will get mad. The bottom line… if everybody uses tabs, they can set their tabstop at whatever position they want.

      • #3205232

        A 100% foolproof way of writing quality code Part I

        by justin james ·

        In reply to A 100% foolproof way of writing quality code Part I

        Tony –

        I am mostly in agreement here.

        Personally, I have a different style that I use on a per-language basis. For example, in Perl, I use lots of underscores and no uppercase letters in variable names. In VB & Java, I use a variant on Hungarian notation.

        This for me is one of the drawbacks of being self taught and having nearly exclusively worked in small shops; no one has ever dictated any kind of coding conventions to me, and I am the only person I know or work with (except for my boss, who prepends every variable name with “my” for some reason…) who even maintains consistency on a project basis for these things. I just have little exposure to a lot of those “best practices” out there, for better or for worse.

        That being said, one suggestion I might make is to not use Pascal for your examples. I know Pascal, and some of the old timers around here might, but it is confusing to the others. As much as I like Perl, I recognize that not many people who picked up coding in the last few years ended up learning Perl. That’s why my examples are almost exclusively in VB.Net code, everyone either knows VB.Net or can at least muddle through it, since its syntax is so… well… basic. Ironically, if I am in a real hurry, my examples are in Perl, because even writing example code is quicker and easier in Perl than VB.Net. While it put a grin on my face to see the bucktoothed rabbits (“:=”), many folks might not be 100% sure about the code. Just a suggestion, not too serious though. It isn’t like your examples are in COBOL or anything (let’s see if I can remember how this goes… “pic variable 9999” gives a 4 digit number, right?).

        J.Ja

      • #3205206

        A 100% foolproof way of writing quality code Part I

        by wayne m. ·

        In reply to A 100% foolproof way of writing quality code Part I

        Unless it was tongue in cheek, I feel Jim-MN missed the entire point of the article.  Software code is not enhanced by slavish adherence to low-level rules.  The rules only need to be applied to ensure nothing detracts from the understandability nor operation of the code.

        Similarly, grammatic rules and punctuation guidelines need only be applied to prose to ensure nothing detracts from the intended message.  I was able to read Tony’s blog post and understand it, and never noticed any grammatic errors, punctuation errors, nor inappropriate allusions.  Given that Tony is a very experienced developer who is voluntarily sharing his knowledge, I feel it is inappropriate to ask him to donate additional time just to meet some literary style guide.

        When reviewing code, one needs to focus on the clarity of intent and the correctness of operation, while giving consideration to the environment provided to write the code.  Likewise, in reviewing a blog article, one needs to focus on the clarity of the message, while taking into consideration the envirionment provide.  There is no professional editor reviewing and correcting blog posts.  There are not grammar checkers nor spelling checkers.  Time is donated.  Despite this, I feel Tony created a good article coverning a hard to describe concept – coding style.

        Tony, please continue to write and do not feel that you need to spend extra time editing and proof reading.  Your comments are valuable, but so is your free time.

         

      • #3205145

        A 100% foolproof way of writing quality code Part I

        by joethejet ·

        In reply to A 100% foolproof way of writing quality code Part I

        Yes, the problem with using code formatters comes with version control,
        diffs and the like. I’m wondering, however, if it makes sense to
        ‘standardize’ on the code formatter and properties? In this case you
        wouldn’t run into the diff problems and the code comes out looking
        pretty standard.

        Just a thought.

      • #3205136

        A 100% foolproof way of writing quality code Part I

        by dbmercer ·

        In reply to A 100% foolproof way of writing quality code Part I

        In re. the issue of code formatting and source control, fifteen years ago, we used ARCS (a variant of RCS) for source control.  ARCS would perform certain actions on check-in, such as attempt to compile it (if it was compilable source).  If the code compiled successfully, it would automatically be incorporated into our development build.  If not (and there are many reasons for checking in uncompilable code), it would not be and no harm done.  I wonder if such a system could also have reformatted the file before checking it in.

        My thoughts are somewhat academic, however, since we have advanced so far in the last fifteen years that we now use Source Safe, which is incapable of much of the functionality of ARCS.  I can only presume that source control alternatives, which we do not use here at my place of employment, are superior to Source Safe and permit this functionality.

      • #3203371

        A 100% foolproof way of writing quality code Part I

        by rushabh_subscriptions ·

        In reply to A 100% foolproof way of writing quality code Part I

        I pretty much agree with what you’ve written here … but the problem why such “standards” have been established is that not every developer is smart. A smart developer always writes good code because he knows the “big picture”, and doesn’t look at just the line that he is writing. A smart developer will also have a better code-reading skill.

        But smart developers are rare, and the rest, which are common … I don’t want to think what would happen if they did not follow the red standards you’ve highlighted above.

        What would happen to you if you, a smart developer, were replacing one who is not ?

        wishes,
        – RD

      • #3203360

        A 100% foolproof way of writing quality code Part I

        by hubert1497 ·

        In reply to A 100% foolproof way of writing quality code Part I

        Naming convention standards –
        The computer could care less whether you use 1-character (“x”) or some monstrously long name (“ThisIsAReallyLongNameForTheXAxis”) to define a field (or routine), it’s going to convert it to a machine address regardless. That being said it’s obvious (or should be) that names are for the Programmers benefit, not computers (or Users).

        Comments are similar (for the Programmers benefit only), and again I agree with you – if the code is well structured, well written, with meaningful names, and “prettified” (for readability), then (generally) comments are unnecessary (“The need for explanation shows a weakness in the text”). I think Cobol was the first language designed for self-documenting code, allowing 30 characters to define field names.

        When I first entered IT, like most of us I saw myself as somewhat of an Artist. Like Wayne M, once I “grew up” I realized Programmers need to be more of a Conformist (especially if you’re consulting), adjusting to the style & standards of whatever shop or client assignment you happen to be working in, because long after you’ve moved on, some other poor slob is going to have to wade through your crap, maybe at 3am. Be a pro and make their task easier.

        Great stuff! Keep it coming. – Rudy

      • #3203355

        A 100% foolproof way of writing quality code Part I

        by jslarochelle ·

        In reply to A 100% foolproof way of writing quality code Part I

        Hi Tony,

        I think this blog was great. Your comments are very much in line with what I think should be the pragmatic common sense approach to coding standards.

        I would like to add that unfortunatly most coding standard are in fact formating standard. It is reassuring for managers to see that programmers have a list of standards that they use and that they can understand. However, this is often a problem because it puts people to sleep and distracts from the more important low-level ()and high level) design issues. How many times I have seen code review reports with numerous violation of the formatting rules and with no real value added.

        Don`t get me wrong here I think you need a minimu7m of formatting however I think that because it is easy to formalize too much emphasis is placed on that aspect.

        I look forward to your next blog.

        JS

      • #3204025

        A 100% foolproof way of writing quality code Part I

        by tony hopkinson ·

        In reply to A 100% foolproof way of writing quality code Part I

        To RD

        Prettifier means you don’t have to bother with indentation at all ever.

        I am a ‘smart’ developer, I don’t need a comment that tells me a for statement is loop, I need a comment that tells me it isn’t even less. Nor does the unsmart devloper.

        Hungarian notation, that’s a little more specific to an environment, it won’t hurt (as long as it’s right!) but it can be redundantt, similarly commenting everything. If they have been consistent about it, you have to find the areas where it actually helps, yourself. If they haven’t been consistent about it, then you can’t trust it, so it defeats it’s own purpose.

        Other People’s Code or even your own after a while, is the hardest thing we have to deal with. That’s essentially what these articles are about trying to graft quality onto a quality neutral product versus just writing a quality product, an saving you me and everybody else a lot of heartache and the people we work for a lot of money.

        I’m not even trying to live up to the title, that was a joke, quality is a context sensitive process, not a method.

    • #3139081

      Writing Quality Code Part II – Design Basics

      by tony hopkinson ·

      In reply to A Blog by a mere developer.

      This is a sort of stage setter, the topic is worth a book or two, so here’s a bit of an introduction.

      All design is compromise. What you could achieve vs what you can achieve. If you go for the minimum your design will cost to adapt, go for the maximum and it will cost more to implement and be more expensive to maintain. We’ve all seen examples of code where to reuse it extensive re-engineering was required, or some undesirable features must be coped with. Whether it’s an edit box that only takes numbers or a form to collect address data, you must think of what uses it is going to be put to. 

      For instance my NumEdit component, should it deal with negatives, take floating point numbers, cope with locale, validate for ranges, allow a flag for marking the numbers as estimated?. If you were going to sell the component, all these things and perhaps more would be desirable as marketable features. If it’s simply to be used in house though, well do you need them? Is it worth the effort of designing so you could build them in later. How likely are you to need them? If you do decide this functionality will be necessary, by all means take a hit now to save a bigger one later, but minimise that hit, if you don’t need the descendant now, don’t implement it, it you aren’t going to call the method now, stub it out. What I try to do is not design something that I will have to rewrite, don’t code yourself into a corner, but remember there is always a way out of one and no one has put you in it yet.

      This sort of ties into my next point as well. I’ve seen many designs, which were bad simply because the designer(s) would not drop an idea when it started to stink. One of the main things you gain from experience in IT development, is recognising when an idea has gone bad before you spend a lot of resource on it. What happens is you spend so much of the budget trying to make a bad design work, admitting that you’ve gone well wrong is very hard. I was guilty of this last year, when trying to re-engineer some legacy code, my idea worked but I broke several other parts of the application. I’d had intimations of disaster, but I was so convinced of my own ability and so wedded to my idea of how it should be, I kept going and going and going. 

      Very embarassing I assure you, I thought I was more practical than that. It does illustrate the point though, the art of coding is to take a complex task and break it up into a set of simpler tasks, so if you are adding complexity, either you misunderstood the complexity of the original task (my mistake in this case), or you are implementing the wrong task. As soon as you find yourself having to take into account more and more, stop, step back and look at the task with fresh eyes based on your new understanding. Another developer to bounce ideas off is invaluable in this process. Even if it’s shouting a TR member for help. In fact sometimes simply articulating the problem, gives you a ‘slap self on forehead moment’ and a quick escape before you advertise how ‘dumb’ you’ve been. Be prepared to have gone wrong, you always will go wrong, it’s part of being creative, part of being productive is to recognise this as soon as possible.

      As a side note this also helps on mission impossible manouvres, you know the one where you get a requirement, that either can’t be implemented and stay in scope , or one where implementing it would result in a pile of unusable rubbish. If a non-technical person gives you a solution to implement, as opposed to the problem they wished to solve, keep a sharp eye out, it’s a prime candidate for this sort of thing.

      So what is a good design ? 

      A long time ago in a faraway place I was taught two basic measures to apply to a design, coupling and cohesion.Coupling is measure of how dependant a design is. The goal is loose coupling because this means any change you make will impact a smaller part of the design. Cohesion is a measure of how spread out a function is a across a design. 

      Coupling is not interconnectedness, that’s useful in a design, it’s dependancy, a thing to be avoided if you can. Obviously you can’t avoid dependancy completely, in fact re-use requires it, what you should do is keep cohesion in mind. Dependancy on an ancestor is one thing dependancy on a sibling, a descendant or even a complete and total stranger is something else entirely.

      The design least likely to achieve loose coupling and tight cohesion is monolithic. There are people who are in love with this approach, personally I don’t have a lot of time for it, it’s a trivial reward in exchange for going badly wrong quickly in my opinion. It encourages dependancies. After all the functionality is already in the code somewhere, why write it again? Dependancy is why, someone makes a change to an invoice routine and now order creation goes nipples up. Yes, Order can be seen to have a relation to Invoice, but not necessarily a direct one, certainly not forcing one to create the other so you can make use of a method, that’s just asking for it. Even if it doesn’t cause a problem now, you can practically guarantee it will in the future.

      So if we chuck monolithic in the bin where it belongs in my far from humble opinion we are left with modular. Yes the clue is in the name, it would be natural to put related routines in a module, it would be equally natural not to go for unnecessary dependancies. You could be in danger of duplicating effort, but that is simply a matter of extracting the common functionality into another module and making both users of the function dependant on it.

      If order and invoice have a common method you have two choices, you could give them a common ancestor and put it in there or you could add it by aggregation, put the common method in a common obect. In this example perhaps delivery or receipt. Either way the dependancy is very clear, the developer knows if they make a change to the common code, they stand a chance of breaking something else. This is where coupling and cohesion pay their way, what you need to change is easier to identify, and the impact of making the change is reduced. 

      Without getting too political the windows operating system is a monolithic design. A lot of their problems, fix this and break something else and the difficulty of spotting that they have broken something is down to using this methodology. You also often see it creep into neglected designs, one’s where there was little or no emphasis on refactoring. Production based demands mean you have to couple your design more closely, simply because you haven’t been allocated the time to do it properly. It dosn’t matter how good a design you start with, in a changing environment it will need changing as well. Refactoring is budgetting for it now, neglect is being forced into a total rewrite in order to compete sometime in the future. 

      Designing for quality is designing for change, not in advance of a particular sort of change, but not designing something that is very expensive to change. Note though these are the ideals from a long term technical point of view, you will be compromising on them throughout your business software career, after all having quality software doesn’t mean you can market it, sell it, make a profit on it, or even that it does what your potential customer needs it to do.Looking at it from a business point of view designing for change reduces the cost of staying competitive, even geeks can see the value in that to a business head.

      So we’ve chosen modular, loose coupling and tight cohesion how do these factors map over to a design?. Very logically is the answer, choose the oposites or end up with them and you look like you are incapable of rational thought. There’s no master plan for this, all you can do is try to keep these two basics in mind and keep in control of where and how often you have to sacrifice them.Next article will be on Object Oriented design and how it can achieve these two measures, along with how you can explicitly undo it and end up with a total mess.

      Damn hard this blogging stuff, been scratching my head how to approach this topic. Most of it is so ‘obvious’ it’s really hard to explain.

      As always comments appreciated.

      • #3140193

        Writing Quality Code Part II – Design Basics

        by justin james ·

        In reply to Writing Quality Code Part II – Design Basics

        Tony –

        Unfortunately, “modular” design all too often becomes monolithic in and of itself. Look at some of the OOP folks out there, and the mountains of code they generate while walking the path of perfect OOPiness! You can’t just take a standard label and say “Hello World.” They need to first create a generic label interface, a label factory, and then an implementation of that interface specific to “classLabelHelloWorld”. Bleh. And then when someone else needs to test, debug, maintain, reuse, or extend their code, you cannot just go to the source of the problem, you need to walk through an object tree that is laid out roughly like the spread pattern of kudzu.

        There is nothing wrong with modularity (in fact, it is the only way to go), but it is important to note that when taken to illogical extremes, the cure becomes the problem.

        J.Ja

      • #3140185

        Writing Quality Code Part II – Design Basics

        by tony hopkinson ·

        In reply to Writing Quality Code Part II – Design Basics

        Object Oriented design and how it can achieve these two measures, along with how you can explicitly undo it and end up with a total mess.

        Now made bold.

        Couldn’t agree more, people keep looking for the panacea. Structured design, top down, reification OO, .Net. “You don’t need a programmer use our softare”.

        OO is a lovely tool, drag and drop IDEs are, high level languages are. However to be any good, the freedom to talk complete rubbish has to be there. It’s no co-incidence that worst designs I’ve ever seen were done in drag and drop Object environments. As though you couldn’t write bad code in them or something.

         

         

      • #3140144

        Writing Quality Code Part II – Design Basics

        by justin james ·

        In reply to Writing Quality Code Part II – Design Basics

        Tony –

        Let’s not forget the people who read Ralph Kimbell before bed each night, and think that if they simply craft the perfect fact and dimension tables, everything will be copesetic. They sit there and agonize over these things, construct the perfect system so their reporting software can auto-detect their perfect relationships and they will have “drag-and-drop reporting”, and BAM! Some user has the *nerve* to come in, enter “real-world” data which does not conform to the database’s specification, and BLAMMO nothing works the way it is supposed to, thanks to some inane error like a cross join… database “experts” are the worst offenders out there, they get so spoiled because a few data items like addresses or basic employee information almost always follows certain hard-and-fast rules, they forget that most data does not follow any rules out there in reality. The result? A system that is technically perfect and utterly useless to the end user. I see this time & time again. The best system is one that works for all parties involved (users, developments, managers, the people who pay the bills), but like you & I both know, someone is always going to be dissapointed; usually either “everyone but the accountants” or “only the accountants.” Good design at a reasonable development pace is nearly always a race between cost and quality.

        J.Ja

      • #3141379

        Writing Quality Code Part II – Design Basics

        by tony hopkinson ·

        In reply to Writing Quality Code Part II – Design Basics

        Only for people who can’t add up.

        I know what you are saying and I thought I had.

        Pragmatic programming eh, who would have thought it. Everybody agrees on more for less, but more of what and less of what. Not talking ideal design here, but the best you can achieve under your current constraints. Basically this means not screwing up your design out of ignorance.

      • #3141340

        Writing Quality Code Part II – Design Basics

        by jslarochelle ·

        In reply to Writing Quality Code Part II – Design Basics

        Tony,

        You’re right, this is a difficult subject and I don’t think there is any magic bullets to be found anywhere (other feedback on your blog  also agre on this). Guess we will have to keep working hard. I agree that fundamental principles like loose coupling, modular design and good cohesion are certainly essential. I also agree with those who point out that keeping the design intact under pressure to ship new features is ultimatly the major problem. More and more I think that part of the solution to this problem is to continuously monitor some of the key parameters in the design such as cohesion, coupling and other parameters (size of classes, etc…). I think it is also important to start doing this early in the project otherwise you get overwhelm with warnings and cannot cope with the amount of work needed to fix the code. Where I work we started using automatic static code checkers and metrics tools as part of the code review process. This has given some good results. One of the interesting impact that the use of such tools has had on the developpers has been to expose them to the key concept like those mentioned previously. The other interesting aspect of those tools is that they will help catch cases where things degenerate despite the fact that separate modifications looked in line with good design principal (inheritance hierarchy getting ridiculously deep and other such problems). Along with the JUnit tests we plan to add some of those validation to the daily build process. Again I am not talking about silver bullets however for us this monitoring has been a good step forward.

        Of course you have to get some commitment from management. Fortunatly for us this is not too bad because clients (Pharmaceutical compagnies) are asking for this and will audit and monitor our practices. Our internal ISO commity will also monitor this.

        JS

      • #3141142

        Writing Quality Code Part II – Design Basics

        by wayne m. ·

        In reply to Writing Quality Code Part II – Design Basics

        Hi Tony,

        Here are a couple of quick reactions (real work intrudes on deeper comments).

        Designing ahead: Don’t Do It – I’ve seen far more cases where the design for future needs has cost more development time than cases where it has saved development time.  Often, future design becomes “sacred code”; no one knows exactly what it is supposed to do or how it is supposed to work, so future developers code around it.  Remember, if it is easy for you to do now, it will probably be easy for someone else to do later.  If it is going to be difficult for someone else to do later, it will probably be difficult for you to do now.  Respect the skills of the developer to follow and don’t feel you need to do the work for him.

        Just One More Build: Prepare to Rollback Changes – I’ve seen too many cases where “This next build will solve the problem” results in looking up at the clock and it is suddenly 1:00 in the morning or 3 weeks after the due date.  Pick a go / no go point and rollback changes if it isn’t working.  In a more recent experience, a developer talked me out of this approach in order to preserve a week’s worth of effort.  As a result, we spent the following 2 months fixing the problem code before rewriting in the 3rd.  If one has picked the right approach, the code will flow easily.  If the code does not flow easily, one has picked the wrong approach.  Being a fan of agile, I usually propose 1/2 day efforts.  At lunch and the end of the day, make a decision to check in code or roll it back.  It is usually much more cost effective to start over from scratch than try to fix a bad approach.

        Modularity and Cohesion: Data versus Functional Cohesion – Classic program decomposition grouped methods based on common operation; one would typically start by calling the initialization group.  Object oriented decomposition groups methods based on common data.  This is one of the  more difficult transitions in thinking related to object oriented approach and purely data based grouping is rare; most systems contain a mixture of both functional and object decomposition.  Please be aware, also, that different decomposition rules apply when multiple computers are used; network communications are expensive.

         

      • #3141113

        Writing Quality Code Part II – Design Basics

        by tony hopkinson ·

        In reply to Writing Quality Code Part II – Design Basics

        Designing ahead yes, implementing ahead no.

        I vaguely remember having this conversation before. there are pros and cons to either argument. Probably business awareness, skill and experience will come into play on how successful you are at it.

        I don’t see what I do as designing ahead, more as keeping my options open. It’s just an extension on not hard coding parameters to me, or not using magic numbers. I don’t implement things I don’t need yet, but I will design so if one of them comes along I don’t have to rewrite it from the ground up. 

        It’s just dealing with those red flag hints from clients like. “Oh no we’ll never need to link order to invoice” !

         

         

Viewing 2 reply threads