Residence of Constants: Interface vs Class

Hi Gurus
I have a very basic question, while defining constants should we put them
in an interface (say MyConstant) or in a class (say XYZConstant). I am sure, as per java guidelines, they should be in a Constant class and should be used as-
XYZConstant.Constant1because that's for interfaces are not designed.
But...putting them in an interface offers a great ease of use. If any class
wants to use couple of constants just implement that interface and use simply as-
Constant1 and not like XYZConstants.Constant1This saves space, as well as keeps the code readable AND by proper naming
of such interface (say UBSConstant) holding only constants, we can pass the message that this interface is not actually an 'interface' but just a constant holder.
Please comment.
Thanks
Anu

... > we can pass the message that this
interface is not actually an 'interface' but
just
a
constant holder.Which is why you shouldn't use an interface forthis
- 'cause that's not what they're for.
http://www.javaworld.com/javaworld/javaqa/2001-06/01-q
a-0608-constants.htmlBelieve me, I have seen constants in interfaces at
numerous places.Believe me, I have seen all manner of things done in numerous places as well, but I don't see that as an argument that such things are correct.
Also even when we know that it's improper to have
interface just for
constants(because the interfaces are not designed for
that), I never
found any disadvantage(If you are talking about the
cohesion, no maintanance
in future would suggest to remove these constants,
moreover I will always
keep my interface in same package and would always
bundle it with any release).
Ok then, with those assumptions I suppose you wouldn't see any disadvantage. I prefer not to assume those things though.
Using Constants in Class, is sometime really
troubling...just imagine long
class name and long constant names (which we would
often have for good
readability..reference Java Naming Standards and put
on top of them that
80 characters / line rule ...again a java coding
standard) turning a line
into two lines...and that code is damn !!!!I tend not to let the amount of typing dictate how I arrange my class hierarchies, but then that might just be me.
setDimensionParameter(
( PropertyControllerConstants.DIMENSION_OF_PROPERTY,
houseSize); This doesn't look bad to me. But again, that might just be me.
>
So is it just! this moral....we should not have
Constants in interface or
should enjoy the freedom of putting qualifier by
implementing constant interface
and using as-
setDimensionParameter( DIMENSION_OF_PROPERTY,
houseSize); Thanks
AnuSo, the maintainer gets to see that all caps unqualified name and check to see if it's a constant in this class, or any super class of this class, or an interface implemented by this class, or an interface implemented by any superclass.
no thanks, I'll just qualify my constants.
But again, that's just me.
Good Luck
Lee

Similar Messages

  • Right way of defining constants - Interfaces or Classes?

    Two widely used ways to define constants in java projects are:
    1. Interfaces - Define constants in interfaces, they automatically become static, final and then implement the interface in concrete classes that need those constants.
    2. Classes - Use normal classes and define explicitly as static, final. Use CLASS_NAME.CONSTANT_NAME to access the constant in concrete classes.
    I have gone through the web on Best-practices for defining constants and its strongly recommended for not using Interfaces for defining constants.
    "The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. " from     Effective Java, Joshua Bloch
    What is your take on this?
    Rgds

    I have gone through the web on Best-practices for defining constants and its strongly recommended for not using Interfaces for defining constants.
    "The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. " from     Effective Java, Joshua Bloch
    I don't like grouping constants into an interface. I prefer keeping them closer to the classes that use them.
    %

  • Use of events and interface in class

    Dear All,
    Could you please explain why we use events and interface in class.
    Also please tell me the use of TRY and ENDTRY.
    Regards,
    Amar

    Events may be a way of communication b/w classes. Imagine you want to call certain code from one class, you would need for that public method, but you don't want to expose it to external user. So you may use events for that. Also events are used to notify that certain state of class has changed (tiggering event). Then all handlers of this event executes and react accordingly.
    Interfaces are a way of provide a service to class which implements it. Imagine that you have class office and hotel and gas station . They don't seems to have something in common. However, there can be some external energy provider which will be an interface. Each class which want to have a lease with this energy provided can implement it (the implementation can differ in some way), so he can provided energy to different classes. This way you will achieve polimorphism (meaning you call one interface method, but code behind it differs from class to class).
    Interfaces are also means of multiple inheritance. One class can implement several service (interfaces). In contrary it can oly inherit from one class.
    Try endtry are just new way of handling exceptions .
    Try to search a litte bit you will find lots of info on the above.
    Regards
    Marcin

  • About interface and class[Please read this]

    I writing what I found out:
    myinterface.java
    interface myinterface
    class A
    A()
    {System.out.println("A()
    of interface");}
    A.java
    class A implements
    myinterface
    A(){System.out.println("A()
    of A.java");}
    public static void main
    (String args[])
    A a=new A();
    //this calls A() of interface
    //myinterface.java
    //how come the output of
    // this code is like this

    how come this is possible?Well, it had to pick one or the other, since they
    have the same symbol name. Why are you choosing to
    make up goofy names that collide in the first place?
    If you want to explicitly use one or the other, you
    need to also choose a package name, and fully-qualify
    the class name that you are trying to instantiate.For example:
    package test;
    interface MyInterface // renamed to follow standard naming convention
      class A
        A() { System.out.println("A() of interface"); }
    class A implements MyInterface
      A() {System.out.println("A() of A.java"); }
      public static void main(String args[])
        test.A a = new test.A(); // prints A() of A.java
        MyInterface.A a1 = new MyInterface.A(); // prints the other one
    }

  • Getting static constants of a class

    hi I have this class:
    package cl.mejorencasa.pedido.modelos
         public class Pedido implements IPedido
            public static const     ENESPERA:String   = "En Espera";
            public static const     ATENDIENDO:String   = "Atendiendo";
            public static const     ENCOCINA:String   = "En Cocina";
            public static const     FUERADECOCINA:String   = "Fuera de Cocina";
            public static const     ENCAMINO:String   = "En Camino";
            public static const     ENTREGADO:String   = "Entregado";
            public static const     PERDIDOPORREPARTIDOR:String   = "Pérdida por Repartidor";
            public static const     PERDIDOPORCOCINA:String   = "Pérdida por Cocina";
            public static const     CANCELADOPORCLIENTE:String   = "Cancelado por Cliente";
            public static const     CANCELADOPORFALTADEPRODUCTOS:String   = "Cancelado Falta Stock";               
    what I want to do is to create a method that gets all the constants of that class and return them in a ArrayCollection. I must say that I want this method to be dynamic, what I mean is that I want it to go through every constant that are in the class. I don't wan't  to add them my self into an ArrayCollection.
    The problem is that I don't know how create such a metho, can someone help me?
    Thanks a lot.
    Sebastián Toro

    To see the statics, I think you have to pass the class itself, rather than an instance of the class, to describeType(). So try
    describeType(Pedido);
    Gordon Smith
    Adobe Flex SDK Team

  • Interface or Class based on the Factory

    Hi,
    I want to write a Factory pattern to decide whether the passed parameter is an interface or class ?
    If an interface is passed then validate whether it is an interface using reflection and do the respective operation similarly for the class as well.
    Please provide your opinion on this.
    Thanks.

    Thanks.
    In the main class I am calling the below :-
    mockInterface("com.test.InterfaceTest");
    protected <T> T mockInterface(String className){
    <T> T interfaceObject = null;
    try {
    Class clazz = Class.forName(className);
    if (clazz.isInterface()) {
    interfaceObject = EasyMock.createMock(className.getClass());
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return interfaceObject;
    Here when I use EasyMock.createMock(className.getClass()) I am getting the below error :-
    "Type mismatch Error saying cannot convert capture#2 of ? extends String to T"
    Here createMock takes class as a parameter as shown below:-
    public static <T> T createMock(Class<T> toMock)
    /* 46 */ return createControl().createMock(toMock);
    What I am doing wrong here? Please clarify.

  • Use Interface of Class object

    Hi Experts,
    I want to use Interface of Class object. But I'dont know how I use it (declaration,call,create etc.)
    There are a lot of exam about using local interface. But I need from Global object.
    Class : CL_TPDA_DIFF_STRUC
    Interface: IF_TPDA_DIFF_SERVICE
    Best regards.

    Firstly ; Your advice book tells the "General OO".
    But I need "Only ABAP OO". The basic logic is the same. But syntax are different.
    If there is a book about ABAP OO and syntax You can advice to me.
    Secondly;
    My code is below.
    I created my interface success . But It give error at runtime. Error mesaage : 'Error during interprocess communication; Debugger will be closed . Message Number TPDA151'
    DATA l_ref_diff TYPE REF TO CL_TPDA_DIFF_STRUC.
    data : xyz  TYPE REF TO IF_TPDA_DIFF_SERVICE.
    data : p_var1 type TPDA_VAR_NAME,
              p_var2 type TPDA_VAR_NAME,
              lv_x type TPDA_DIFF_ATTR.
    data : l_it_value_diff TYPE TPDA_DIFF_VALUE_DIFF_IT,
              l_it_main_diff TYPE tpda_diff_main_diffs_it.
    p_var1 = 'CLIENTDATA1'.
    p_var2 = 'CLIENTDATA2'.
    lv_x-maxhits = 100.
    CREATE OBJECT l_ref_diff.
    xyz ?= l_ref_diff.
    xyz->init( ).
    xyz->DIFF( EXPORTING p_var1 = p_var1
                         p_var2 = p_var2
                         p_diff_attr = lv_x
               CHANGING p_it_value_diff_it = l_it_value_diff
                        p_it_main_diff_it  = l_it_main_diff ).
    Best Regards.

  • Deleting interfaces from class

    hi to all
    I am trying to delete interfaces from class . But it showing that "You cannot perform this action in modification/enhancement mode". where is the problem.
    thank you

    Hi,
           This error comes up when the object you are trying to edit has original system as something else. This is a protection given by the modification assistant, so that the changes to the objects are recorded. If you know what you are doing(modifying objects in non-original system), go to edit menu and select modifications and select "switch off modification assistant".
    Regards,
    Arun Prakash

  • Ordered & unordered arraylist with interface & abstract class

    you can remove this
    Edited by: Taco_John on Mar 9, 2008 7:38 PM

    http://www.google.com/search?q=java+interface+%22abstract+class%22
    http://www.google.com/search?q=java+method+overloading+overriding

  • Interface & abstract class

    1>whats the basic difference between an interface and an abstract class?
    when should one be using an interface or an abstract class?
    2>whats the difference between method overriding and method overlaoding?
    does both of them has any relation with the instance of te class implementing them?

    http://www.google.com/search?q=java+interface+%22abstract+class%22
    http://www.google.com/search?q=java+method+overloading+overriding

  • [svn] 4081: Remove @private from an interface and class

    Revision: 4081
    Author: [email protected]
    Date: 2008-11-12 06:50:02 -0800 (Wed, 12 Nov 2008)
    Log Message:
    Remove @private from an interface and class
    QE Notes: None
    Doc Notes: None
    Bugs:
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/listClasses/ListBaseContentH older.as
    flex/sdk/trunk/frameworks/projects/rpc/src/mx/messaging/messages/ISmallMessage.as

    System.arraycopy()
    You're almost certainly better off with a List implementation, though. Whether you use LinkedList or ArrayList should depend on your usage specifics, but from the limited information provided it seems that LinkedList would be a better choice.

  • Interface and Class

    Hi pls any one can help me ?. In most of all the places we are declaring the constance in class files as
    class A{
    public static final String str_Constant;
    After that we will refer this like "A.str_Constant"
    Why we cant define it in interface like
    interface A{
    String str_Constant;
    and refer like A.str_Constant
    Thanks in advance

    Not static either:The "static final" modifier is implied, since it doesn't make sense to have non-static, non-final variables in an interface. The way to go is to do this:
    public interface Constants {
       public static final int SOME_CONSTANT = 0;
    }This works if you have package-spanning consants (such as SwingConstants), but if you have class-specific constants you should gather them inside the class:
    public class Stylesheet {
       public static final int BACKGROUND = 0;
       public void set(int arg, Object value) { ... }  
    myStylesheet.set(Stylesheet.BACKGROUND, Color.white);But this doesn't look very good (see enum's in 1.5), so it's probably better do solve it in some other way (depends on the project).
    Regards,
    Nille

  • Constants for PDFBookBinder class

    I can't find the Constants class/interface for the valid contants when calling PDFBookBinder class. Can someone post a URL?
    So far the only valid ones I know of are from examples:
    PDFBookBinder pdfBookBinder = new PDFBookBinder(ctrlFile, pdfFileName);
    Properties prop = new Properties();
    prop.setProperty(Constants.SYSTE_TEMP_DIR, location);
    prop.setProperty(Constants.SYSTEM_CACHE_PAGE_SIZE, Constants.NUM_50);
    prop.setProperty(Constants.PDF_COMPRESSION, Constants.BOOLEAN_TRUE);
    prop.setProperty(Constants.PDF_TITLE, "Custom PDR");
    prop.setProperty(Constants.INCLUDE_TOC_PAGE_NUM, Constants.BOOLEAN_TRUE);
    pdfBookBinder.setConfig(prop);
    Thanks

    Here is what we did in similar situations:
    In the EO project (which is normally deployed only on the app server) we created an interface that contains these constants. The corresponding entity implements this interface and makes use of the constants according to the business rules.
    BUT, from deployment point of view, the interface is deployed to a different JAR, which is used by the EO JAR (so, it's deployed on the server-side), but is also accessible on the client-side.
    So, in the client-side implementation of the module, the interface is accessible and the same constants may be used.
    The same approach stands for a VO.
    We finally extended this mechanism to "publish" on the client even the attribute IDs for EOs and, mainly, VOs.
    I know there is a recent related thread on this topic, but I'm having lots of problems with the forum navigation lately :>( I will post the link asap.
    HTH,
    Adrian

  • Http interface with class

    HI EXPRTS!
    i am working on the Class which is the copy of CL_HTTP_EXT_CSIF
    BUT I HAVE USED OPEN DATASET for Create,Get and delete comands. which is used to interface with HTTP.
    when i execute the same with using Url i am geeting correct resules but when i try to create file using RSHTTP80/90/70/71 standerd reports its creating a file but giving a status as 500 internal server/time out error.
    can you please tell me what might be the proble,.
    answers will be rewarded
    mahesh

    Problem solved. The key is that every ejbCreate method NEEDS ejbPostCreate iwth exactly the same signature.
    Solution source: http://www.thatsjava.com/java-enterprise/24282/ see comment #4

  • It should be interface or class ?

    Friends,
    I have a major entity in my application. That entity is, u can say, heart of the what application does.
    Actually, clients can open up a case with supplier and that case is my main entity.
    Now that case can be of any type out of some 7 types. And all of them have some data common say around 40% data is common. and remaining varies from type to type.
    Now, my problem is, this main entity class should have any interfact on the top to depict common methods ? I feel that, it should be an abstract class with these common methods being abstract methods. Well, we have abstract class also, but it is used to store only common variables, not methods. Moreover we have impl classes also.
    What you guys say ? Is there any design principle, which makes this interface must ??
    Thanks.

    Make it both. Follow the lead of the java.util.List and java.util.AbstractList.

Maybe you are looking for

  • Help needed in Interactive report

    Hi, my requirement is: in first list, i have to display some sales orders from vbak. in second list, user has to select multiple sales orders by check boxes besides them & click on execute. in third list, sales orders(which is selected in second list

  • Media Encoder Dynamic Link error 5027 :: 12  ????

    While trying to send a file to media encoder from after effects in order to render in a file format not located within ae i was given an error message that my adobe media encoder was not installed 5027 :: 12 dynamic link server failed . When i launch

  • When I delete a tab, next time I open Firefox it is back! I deleted it from Bookmards - How do I get rid of it permanently?

    I have two tabs that I want to delete. I went to Show All Bookmarks, selected them on the list, held down the command key, clicked on Organize and deleted them. I exited Firefox. When I opened it again, the tabs that I had deleted in my Bookmarks wer

  • Problems syncing with nano 5th gen

    I recently purchased a new computer. My 5th generation Nano was working perfectly fine with it until this morning when I tried re-syncing it with new music and it told me I had to restore it. I tried the iTunes restore 3 times and it still refuses to

  • "Services for object" for SD document POSITION not header

    Hi, Could you tell me if there is a possibility to create attchment for a postion of SD document not a header? I would like to see that ex. position number 20 has an attachment. It would be great aslo to see an icon for position or any other flag. Co