Good programming practice

There are 2 sets of code which I extracted from a dummy book. The author just want to illustrate 2 ways that we can capture an exception.
Code set 1_
import static java.lang.System.out;
class GoodNightsSleepA {
    public static void main(String args[]) {
        out.print("Excuse me while I nap ");
        out.println("for just five seconds...");
        takeANap();
        out.println("Ah, that was refreshing.");
    static void takeANap() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            out.println("Hey, who woke me up?");
Code set 2_
import static java.lang.System.out;
class GoodNightsSleepB {
    public static void main(String args[]) {
        out.print("Excuse me while I nap ");
        out.println("for just five seconds...");
        try {
            takeANap();
        } catch (InterruptedException e) {
            out.println("Hey, who woke me up?");
        out.println("Ah, that was refreshing.");
    static void takeANap() throws InterruptedException {
        Thread.sleep(5000);
}To u guys who are experienced java programmer out there. Which set of code do u think is better coding practice and u'll usually code that way ? I personally would say GoodNightsSleepA is a better practice. Or u guy have some other better suggestion ? Thank you.

Thank you to everybody who responded to this thread. Can anyone pls point me to a link that talks about proper OOP system analysis and design. I believe I need some foundation on this, otherwise I can't write a proper scalable code. Like some of u has pointed that the GoodNightsSleepB class will be more appropriate coz it provides flexibility to other user who would like to use it as a subclass. I didn't thought of this b4 until u guys have enlighten me.
To corlettk, I'm totally new to AOP. I just read some of the links from the google search result. I'm still in a very blur stage about AOP. Am I right to assume that we should only code to include basic business requirement functions(primary task) in our class and make use of AOP to do the secondary task(such as data verification/exception capturing) ? Pls correct me if I'm wrong. Thank you in advance, guys.

Similar Messages

  • Good programming practices:   creating Iterator objects

    Hi,
    This is a question about Good programming practices for creating Iterator objects of ArrayList objects. The following line of code works fine in my program (as ridiculous as it may sound):
            Iterator cheesesIterator = cheeses.iterator();but I was wondering whether Java is automatically inserting the <Type> and new code to make:
            Iterator<String> cheesesIterator = new cheeses.iterator();and therefore whether it is good practice to use these everytime? Thank you. ("full" code shown below:)
    import java.util.ArrayList;
    import java.util.Iterator;
    public class DemonstrateIterator
        private ArrayList<String>  cheeses;
         * constructor:
        public DemonstrateIterator()
            cheeses = new ArrayList<String>();
            cheeses.add("Emmentaler");
            cheeses.add("Cheddar");
            cheeses.add("Stilton");
            cheeses.add("Brie");
            cheeses.add("Roquefort");
        public void listCheeses()
             //make an iterator object of the ArrayList object
            Iterator cheesesIterator = cheeses.iterator();
            while (cheesesIterator.hasNext()) {
                System.out.println(cheesesIterator.next());
            /** Exploring the toString and Super functions. **/       
            System.out.println("\na toString call to Super returns: " +
                                              super.toString() + "\n");
    }

    AJ-Phil wrote:
    Hi,
    This is a question about Good programming practices for creating Iterator objects of ArrayList objects. The following line of code works fine in my program (as ridiculous as it may sound):
            Iterator cheesesIterator = cheeses.iterator();but I was wondering whether Java is automatically inserting the <Type> and new code to make:
            Iterator<String> cheesesIterator = new cheeses.iterator();and therefore whether it is good practice to use these everytime? TFirst, new chesses.iterator() won't compile.
    iterator() is just a method that returns an iterator. It constructs an instance of a private or nested class that implements iterator, and returns a reference to it.
    As for the <T>, when you declare List<String>, that parameterizes that list with type String. The iterator() method returns Iterator<T>. You can look at the source code for yourself. It's in src.zip that came with your JDK download.
    Separate from that is your declaration of that variable as type Iterator, rather than Iterator<String>. Regardless of what you declare on the LHS, the iterator() method returns Iterator<T>. Your bare Iterator is essentially Iterator<Object> or Iterator<? extends Object> (not sure which, or what the difference is), which is assignment compatible with Iterator<T>. If you had declared it Iterator<String>, you wouldn't have to cast after calling next().
    Edited by: jverd on Nov 23, 2008 11:33 AM

  • Good programming practice - Abstract class

    Hi all,
    I have been trying to help another soul in this forum, and came to the conclusion that I don't know good
    programming practice when it comes to abstract classes.
    Is this correct?
    You CAN implement methods in an abstract class, but it's not recommended.
    I have NEVER done this...when is there possibly a need to?
    Regards.
    / k

    Yes, absolutely, you can implement methods in an abstract class. Any method that all subclasses will perform in the same way can be implemented in the abstract base class. If subclasses perform similiar functions depending on their type you declare those as abstract in the base class. Here is a contrived example that I have seen on job interviews.
    Suppose your developing an application that draws on a panel. We want to provide some canned shapes such as a circle, a square and a triangle. We want to be able to draw the shape set or get its color and calculate its area.
    Let's define an abstract base class Shape
    public abstract class Shape{
        private Color myColor;
       //  since color has nothing to do with what kind of shape we're working with, create concrete implementation
       public Color getColor(){
            return myColor;
    public void setColor(Color newColor){
       myColor = newColor;
    // however, drawing the shape and calculation its area are depending on the actual shape.
    public abstract void draw();
    public abstract double getArea();
    // so then Square would be something like
    public class Square extends Shape{
       public double get Area()
          return sideLength * sideLength  // assumes somehow we know sideLength
    public void draw(){
                  // concrete implementation
    }we can do the same things for Circle class and Triangle class.
    And, if you think about it you'll notice that we could have made a Rectangle class and then Square would be a subclass of Rectangle where both dimensions are equal.
    I hope that somewhat strained example helps answer your question.
    DB

  • Do IOS app developers follow any good program practices?

    I've had my iPad (original) a little over two years now, and I can say without a doubt, it is the most unstable platform I've used in nearly 30 years of using computers.  Most apps crash routinely, usually while at least one other app is running in the background.  Unloading the crashed app from memory and reopening uually works, but is a huge nuisance (and reason enough to me why iPads are not business-ready, except for specific task applications requiring mobility).  As one trained in both software and systems engineering, with 20 years IT experience mostly in engineering, I have to conclude that IOS app developers use "code and fix" development, with little testing before release.  Of course, in theory it could be that IOS itself isn't well designed to handle multitasking and doesn't provide adequate process isolation.  Either way, it makes for a frustrating experience as a user.
    Has anyone else had similar issues?  Thoughts on why?

    The original iPad does poorly with multiple apps open, the memory is just too small at 256 MB.  The processor is very slow compared to those in the current generation iPads.  And then couple that with developers who are for the most part independent of Apple and merely submit there products to Apple and you get a totally unpoliced set of apps.  Some are true professionals and follow very good programming practices, one that comes to mind is the GoodReader PDF reader.  Very stable and very powerfully built.  then you get into the gamers and Is is almost like they never heard of writing effecient, compact code.
    The issue I see is a tightly controled operating system, with app developers handed a set of specs under which to code, but no real controls other than does the app run and is it free of malicious code.
    Just some thoughts.

  • Examples for good programming practice with multiple DAQmx tasks

    I'm writing a program to continuously log data from 8 counters, 8 encoders, and 8 voltages. The proof of concept VI with a single counter was simple and elegant, but scaling up to all signals resulted in a wiring mess. I've been working through the Labview Core courses, and am currently on Core 3. I still haven't come across a discussion on how to work with multiple DAQmx tasks without making a mess of the block diagram. Can anyone point me in the right direction?
    Also, say I have a state machine that has a configure, idle, and logging states. I need to set the initial values of the encoders during configuration, and keep up with their changes while in the idle state so I have appropriate starting values when entering the logging state. Can anyone point to an example that shows how this might be accomplished?
    Thanks

    I'm very familiar with AE's/Functional Globals - but I have struggled in the past with handling multiple DAQmx tasks - particularly when you're using multiple devices and using different types of measurements which require seperate tasks/handling (e.g. such as thermocouples which require extra compensation).
    I'm not even sure I know whare the requirements are for needing multiple tasks - I know you can need multiple tasks for a single device if the type of measurement is different but can you share an Analogue Input task amongst multiple devices?
    I think in hindsight (and without too much thought now) it looks like a good case for Object Oriented LabVIEW - with a base DAQmx class (initialise, configure, start, acquire, stop, close etc.) and then child classes for each type of measurement (with one task associated with each - and private data unique to that specific class). You then hold an array of objects (one for each task) and iterate through each one with dynamic despatch to get the data.
    I don't know your particular experience level of using LabVIEW (and as such, OO may not be appropriate) - but as a wider discussion of 'best practice' it seems like an appropriate method I would use going forward.
    Certified LabVIEW Architect, Certified TestStand Developer
    NI Days (and A&DF): 2010, 2011, 2013, 2014
    NI Week: 2012, 2014
    Knowledgeable in all things Giant Tetris and WebSockets

  • "Good programming practice" question about writing classes

    I am taking a java class this year and my teacher has taught us to never use global variables in a class (but still private). I find it much easier to explain with a simple example. Say I have a class that looks like this:
    public class Demo
            private int int1, int2;
         public Demo()
              int1 = 1;
              int2 = 2;
         public void demoMethodOne(int int1, int int2)
              //... code using the ints passed to the method
         public void demoMethodTwo()
              //... code directly accessing the private ints of the class
            public int getInt1() { return int1; }
            public int getInt2() { return int2; }
    }My teacher says to ALWAYS use methods of the type demoMethodOne (to pass all of the variables it will use to it) and avoid using the type demoMethodTwo. But in my programming experience, I have found it very repetitive and pointless to use that method in some cases. For example if I call demoMethodOne like this:
    demoMethodOne(demo.getInt1(), demo.getInt2());
    That seems very repetitive but that is how I am told to do it. Should I program that way even if it seems very pointless or is it ok to use "public" variables like in demoMethodTwo. Thanks.

    I think you may have misunderstood your teacher.
    If your object method is doing something with the object's state, then it's perfectly appropriate to modify the object's fields, which embody the state.
    And generally it's good to adopt a functional programming approach, in which there are few side effects. This principle is sort of independent of the previous one.
    The danger is when you treat object fields as global variables (and not as the embodiment of the object's state). In this case the global variable doesn't really represent anything, it's just a place to store data temporarily to avoid designing your methods properly. So for example you'd have two methods, one sets a field and then calls another method, which reads the field; the field doesn't really mean anything to the object as a whole, it's just a lazy way to pass data between the two methods. This is asking for bugs. The correct thing would have been to pass the value as an argument to the second method.
    Also, if you have a method that doesn't really express the behavior or effect the state of an object, but is called just for its return value (like some kind of utility method), then it's pointless and dangerous to make it effect the state of an object.

  • Is this a good programming practice?

    Putting a "throws Exception" in the constructor.
    class Test
    public Test throws Exception {
    }

    I read somewhere that the possibility that something can go wrong in a constructor is one of the convincing arguments for having exceptions in the first place, since there's really no other (reasonable) way to report an error back to the caller. So yes, have a constructor throw an exception (and declare which one(s) it may throw) is a very fine practice as far as I'm concerned.
    I agree that "throws Exception" is poor practice for all methods. Much better to write "throws Exception1, Exception2, Exception47, ExceptionA, YetADifferentExceptionClass" even if it takes a couple of lines.
    Message was edited by:
    OleVV

  • Good programming practices

    I'm writing a straight forward database app with Java to do the logic and GUI. I have a User class and a "create" method to create a new user. In my database, the user table has a bunch of fields (the typical name, address, etc, etc), but only a few are required. I'm trying to figure out the most proper way to do this.
    It would be much easier on the client programmer to pass some sort of hash, but I'd imagine this would generate bad documentation. If I required them to pass 30 parameters, it would get very annoying very quick, but it would generate easy to read api documentation that would play well with IDE's. How would you guys tackle this? Lot's of parameters and good javadocs, or 1 hash and bad generated api documentation.

    cbaechle wrote:
    That's the correlation to the database table. There's a lot of info that can be stored on a user. username, password, email, address, city, state, zip, home phone, cell phone, work phone, etc, etc. It adds up quick and honestly, separating them out will needlessly make it more complicated than need be. I could make an address class I suppose, but for the intention I doubt it would ever be useful.It'll be useful when a single person can have two addresses (e.g., home and office) or when two people live at a single address (data normalization).
    It's the standard way to design a database schema.
    I don't think it's more complicated to have addresses separated out. It's easier to grok because the data is grouped into meaningful bunches. Why would your username be tied to your work phone number?

  • Any usefull examples of good coding practice in large programs

    Hi, ive been writing code for about 10 years now. Know a good bit about labview now lmao! But want to get to know good code practices e.g. in creating large programs, code templates, avoiding race conditions, use of multiple loops and to be able to write code for clients as a contractor. Any one help me??
    Stu
    Solved!
    Go to Solution.

    Check out thelargeapp community and this KB article
    Message Edited by Jeff Bohrer on 06-14-2010 04:49 PM
    Jeff

  • General programming practice question (possibly re: clusters)

    I apologize for this probably being an old topic or something I should have found elsewhere, but I simply didn't know what to search for.
    I am tackling my first labview program of significant scale, and quickly discovering that the difficulty of wiring scales exponentially with the number of things you're trying to do.  I marvel at the short and sweet pieces of code people post on here, and try my hardest to replicate the style to no avail.
    If I've missed a good guide for good organizational practices when programming, please point the way!
    Essentially, I'm grabbing info from a video signal via a daq card, using this to compute the location of objects in the video, and sending instructions to a robot to control its movement-- this means I have the image wires, serial wires, integer wires for pixel values, real wires for coordinates coordinates, and error wires flying around.  It's not an extraordinary amount of data but it seems to be an extraordinary amount of scooting things around to make things look pretty and/or readable, every time I make a change.
    Clearly use of subVIs is the way to go for each of the tasks, but I still have several pieces of data that need to be communicated from each task to the next.
    Is it common practice to cluster the data even if it's unrelated, just to simplify the wiring?  Is there significant overhead if you're unclustering and re-clustering it in each subVI?  (I tried to write a quick benchmark program but I couldn't quite figure out how to use the profiler)
    Any general veteran tips would be much appreciated!

    Check out the following links: -
    http://www.bloomy.com/resources/index.php#pres
    Specifically here the Powerpoint presentations (five_techniques_for_better_labview_code.pps)
    Some additional pointers/ resources below: -
    http://forums.ni.com/ni/board/message?board.id=LVETF&message.id=1
    http://zone.ni.com/devzone/cda/tut/p/id/4434
    http://openg.org/tiki/tiki-index.php?page=Style%20Guide
    There is a host of other information out there as well, try Google and use the term 'LabView style guide'.
    Hope this helps put you on the right track.

  • Good programming tactics

    hi. i thought i'd like to start a thread on good programming tactics.
    ill start with a few questions:
    interfaces, abstract classes, and polymorphism, when are they REALLY useful?
    (and how does one REALLY use them?)

    Interface � An interface is like an agreement between you and another programmer. An example would be if you designed some software that needs an XML parser and you used an old XML parser that you wrote a few years ago. You know that the parser is not really, really good code but it�s good enough for your program. You also know that maybe someone who wants to use your code may want to add his or her own XML parser that work much better.
         If you use an interface to access the original parser in your code then you can give them the ability to rapidly add their own parser. What the interface does is give the other programmer a set of routines that he must have to work correctly with your program. If he can write a better parser that supports all these routines then he can use it and the interface is the guarantee that the compiler will use to verify that his program has all the proper methods to work with your program.
         Note: Some programmers use interfaces as a way to inherit multiple classes. java does not support extending (read inheriting) more than one class so a common way to get around this is to use interfaces which is not exactly the same but is the way to support this in java.     
    Abstract Class � An abstract class is similar in use to an interface. Where an interface is only a group of methods without any code, an abstract class is class that can never be created (instantiated), can have runnable code and will normally have some abstract methods which are similar to the methods in an interface.
    You can only use an abstract class to create other classes using the keyword extends and it must have it�s own version of every method that is abstract in the original abstract class. The use of abstract methods forces the programmer who uses your class to write methods that are necessary for the class to function correctly.
    An example of where to use this would be in graphics classes. You might have an abstract class called GraphicObject. This class would have several useful calls to methods ( i.e. setColor() ) and several useful fields and it might also have an abstract method called draw.
    The programmer would have to write a method to draw his GraphicObject as a circle would be drawn different than a rectangle.
    The original programmer knew that if you wanted to use his class GraphicObject then you must write a routine that will draw your GraphicObject. The absract class will take care of accessing the graphics card and setting up the environment to draw the object.
    The following I borrowed from http://www.developer.com/tech/article.php/983081 where you can read more about poly morphism if you want to. As you can see polymorphism is directly involved with interfaces and abstract classes.
    What is polymorphism?
    The meaning of the word polymorphism is something like one name, many forms.
    How does Java implement polymorphism?
    Polymorphism manifests itself in Java in the form of multiple methods having the same name.
    In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods, which were discussed in a previous lesson).
    In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).
    Three distinct forms of polymorphism
    From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
    Method overloading
    Method overriding through inheritance
    Method overriding through the Java interface
    Hope this helps and doesn't confuse you more. I am sure that someone is going to find things to correct but I believe the general ideas are right.

  • What's a good program to use to make flyers and handouts with?

    What's a good program to use to make flyers and handouts with? I'm not a wiz with computers so nothing too sophisticated is needed. Thanks!

    Pages would be fine but there are hundreds, I'd recommend using the Mac App Store.

  • What is a good program to install windows via a flashdrive...Have the iso

    What is a good program to install windows via a flashdrive...Have the iso...

    What are you trying to do?
    You can install Windows in a Boot Camp partition and have a Dual Boot system where you run one operating system at a time. Either Windows or Mac OS X.
    Or you can use one of the 3 available virtual machine software parograms to install Windows in a virtual machine on top of Mac OS X. Then you can run both Windows and OS X at the same time.
    If you go with the Boot Camp option then you really need to burn that ISO file onto a DVD disc as Boot Camp likes to install from disc.
    If you go with the virtual machine option then you can use that ISO file as it is to install Windows. You will just point the VM to the USB thumb drive to find the Windows OS to do the install from.

  • Is Windows A Good Program To Use On Mac?

    I have a macbook and i would like to know, is it a good program to use on a macbook or any mac?

    Windows is not a program. It's an operating system that you run programs on. Whether or not you install Windows on you Mac is up to you. What is making you think you should install it? Do you have Windows only programs you need to run?

  • I am looking for a good program to edit existing websites for about $99.00

    I am looking for a good program to edit existing websites for about $99.00 or less, any suggestions?
    Thanks,
    New MacBook owner.
    Martin

    Welcome to Apple Discussions!
    http://www.barebones.com 's Textwrangler. Use http://www.anybrowser.org/ as a guide for good HTML composition.
    If a web editor does not give you power to do full text editing and claims to be WYSIWYG, don't believe it. Chances are, it uses assumed standards of specific browsers, which are not fully http://www.w3.org/ compliant.

Maybe you are looking for

  • How to turn off default attribute "Validity" in a web-report

    Hi Experts, We are using 0ORGUNIT with time-dependent hierarchy. This hierarchy is included in most of our reports. When we run a report with 0ORGUNIT hierarchy an attribute "Validity" is always shown next to the hierarchy. We can manually remove thi

  • Mac mini late 2012 not working with small VGA monitor

    I got a mac mini (late 2012 10.8.4 all updates installed) and it is working fine with samsung b2230 via VGA adapter. There is a small VGA monitor (PL8006 max at 1024*768) which works fine when connected  to a PC. When I connect the small VGA monitor

  • Code to get the all Records in Work Book

    Hi, I have a Report to show on work book, Now I am used REFERENCE to get the data. In Work book i have used formula for one cell and i draged that to few rows(for example 100). Here my problem If i get below 100 records there is no problem, if it exc

  • Guide layer stops working when I change a movieClip

    Hey all, So I have a few things moving along a common guide layer. There are 7 objects, and depending on what is happening on screen, i want to have some of the objects appear and disappear. I have all of the objects _alpha set to 0, but when somethi

  • I have a Mac book 2.4 with 2gig DDR2 667mhz ram

    My questions can this be upgrade to 4 Gig? can the 4 Gig consist of DDR3 modules? can the upgrade be higher than 667mhz and if yes how high can I go? thank you in advance