Results 1 to 20 of 20
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default confusing name repite

    Still studying many code examples and stumbled over the next issue.

    The action listener gets the name of a file from a menu item, than
    the next method "openFile" (note the name) from a different class "FileManager"
    opens a file like this: File openFile new File(fileName), see the code fragment down!

    The confusing part is that "openFile" is the name of the method,
    but at the same time it is declared as field "File openFile;" at the class "FileManager"
    Why is that, or is that a mistake?
    (When I change the name of the method things still work….)



    Java Code:
    menuListener = new ActionListener() { 
    	public void actionPerformed(ActionEvent evt) { 
    		JMenuItem mi = (JMenuItem)(evt.getSource());
    				String fileName = mi.getActionCommand(); 
    		try{
    						String text = fileManager.openFile(fileName); 
    			textArea.setText(text); 
    			addRecentFile(fileName);
    		} catch (IOException e) { 
    			// Do nothing - message already printed
    				}
    	}
    };
    
    
    
    File   openFile;
    
    public String openFile(String fileName) throws IOException,
    								FileNotFoundException {
            this.fileName = fileName;
            openFile = new File(fileName);
            try {
                canWriteFile = openFile.canWrite();
                FileInputStream fs = new FileInputStream(openFile);
                long l = openFile.length();
                byte[] content = new byte[(int)l];
                fs.read(content);
                fs.close();
                return new String(content);
            } catch (FileNotFoundException e) {
                	System.out.println("Failed to open " + fileName + ".");
                	Toolkit.getDefaultToolkit().beep();
                	throw e;
            } catch (IOException e) {
                	System.out.println("Failed to read " + fileName + ".");
                	Toolkit.getDefaultToolkit().beep();
                	throw e;
            }
     }

  2. #2
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: confusing name repite

    Hmm that's asking for opinions really. I call it a mistake, you shouldn't use confusing naming schemes and having duplicate names is very confusing. But it is not technically wrong, the compiler is perfectly capable of knowing when you're referring to the variable and when you're referring to the method; its only more difficult for humans.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  3. #3
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    Gimbal2 the code is not mine but from the JFC book, and I wondered if there would be some deeper meaning
    for this name occurrence? I mean it could be that I am missing something here.... but probably not, right?
    Thanks.

  4. #4
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: confusing name repite

    > I mean it could be that I am missing something here.

    Anything is possible, even the most awesome software engineer on the planet can miss something. But until you see proof that there IS a deeper meaning, let your logic mind guide you. What do you think? Is there a deeper meaning or not? If so, what might it be?

    If you can't answer it: better to just move along. If you miss something you'll run into it eventually.

    And no, there is no deeper meaning, its just ugly code ;)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  5. #5
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    So I did do a test, I changed the name of the method into openFileS and changed all method calls accordingly....
    But when running the thing nothing different happened....
    So that made me conclude that it might be a "mistake", since there was no further consequence for the name double!
    But that human mistake did not bother the machine, right as you explained!

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: confusing name repite

    Now for the bonus points: which name would you change (that of the variable, or that of the method) and to what would you change it?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    I would change (and I did try that out) the method's name?
    But let me articulate my problem with the double name a little better.
    The most confusing part of the code is the line:
    canWriteFile = openFile.canWrite();
    Ok the canWrite method set a simple boolean canWriteFile like this:

    Java Code:
    public boolean canWrite() {
            return canWriteFile;
        }
    So my question to you is, why is that line not simply be like this:
    canWriteFile = canWrite();
    Which makes even less sense...
    Assuming that the method invokes the file not the method, right?

    In other words: I do not understand what
    canWriteFile = openFile.canWrite();
    is actually doing!
    Last edited by willemjav; 12-12-2013 at 10:46 AM.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: confusing name repite

    The canWrite() method is part of the File class, not part of the class containing the openFile() method.
    So it needs to be called via an instance of File.

    And, personally, I would have changed the attribute.
    Indeed, unless it's used somewhere else in the code, I would reconsider whether it is an attribute at all.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    No tolls they are both part of the same class!
    Here is the complete setup of both classes:

    Java Code:
    package swing;
    
    import java.io.*;
    import java.awt.Toolkit;
    
    // Helper class to manage an open file
    public class FileManager {
        
        // Check whether a named file exists
        public boolean fileExists(String fileName) {
            return (new File(fileName)).exists();
        }
    
        // Open a new file
        public void newFile(String fileName) throws IOException {
            if (fileExists(fileName)) {
                System.out.println("File <" + fileName + "> already exists.");
                throw new IOException("File exists");
            }
            this.canWriteFile = true;	 // Assume we can write
            this.fileName = fileName;
            System.out.println("this is " + this);
        }
    
        // Open a file
        public String openFile(String fileName) throws IOException,
                                                FileNotFoundException {
            this.fileName = fileName;
            openFile = new File(fileName);
            try {
                canWriteFile = openFile.canWrite();
                FileInputStream fs = new FileInputStream(openFile);
                long l = openFile.length();
                byte[] content = new byte[(int)l];
                fs.read(content);
                fs.close();
                return new String(content);
            } catch (FileNotFoundException e) {
                System.out.println("Failed to open " + fileName + ".");
                Toolkit.getDefaultToolkit().beep();
                throw e;
            } catch (IOException e) {
                System.out.println("Failed to read " + fileName + ".");
                Toolkit.getDefaultToolkit().beep();
                throw e;
            }
        }
    
        // Save to the file
        public void saveFile(String text) throws IOException {
            if (fileName != null && userWantsWrite == true && canWriteFile == true) {
                openFile = new File(fileName);
                try {
                    FileOutputStream fs = new FileOutputStream(openFile);
                    byte[] content = text.getBytes();
                    fs.write(content);
                    fs.close();
                } catch (FileNotFoundException e) {
                    System.out.println("Failed to open " + fileName + " for writing.");
                    Toolkit.getDefaultToolkit().beep();
                    throw e;
                } catch (IOException e) {
                    System.out.println("Failed to write to " + fileName + ".");
                    Toolkit.getDefaultToolkit().beep();
                    throw e;
                }
            }
        }
    
        // Save with a different file name
        public void saveAsFile(String fileName, String text) throws IOException {
            this.fileName = fileName;
            if (userWantsWrite && canWriteFile == true) {
                saveFile(text);
             }
        }
    
        // Close the open file, writing data if required
        public void closeFile(String text) throws IOException {
            if (isFileOpen()) {
                // Write file content
                saveFile(text);
            }
            fileName = null;
            openFile = null;
        }
    
        // Make the file writable or not
        public void setWritable(boolean writable) {
            this.userWantsWrite = writable;
        }
    
        // Check whether we have an open file
        public boolean isFileOpen() {
            return openFile != null;
        }
        // Check whether we can write to the file
    
        public boolean canWrite() {
            return canWriteFile;
        }
    // Get current file name
    
        public String getFileName() {
            return fileName;
        }
        File openFile;	 // File object for open file
        String fileName;	 // Name of current open file
        boolean userWantsWrite = true;
        // User wants to be able to write
        boolean canWriteFile = true;
        // File can be written to
    }





    Java Code:
    package swing;
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    
    public class MenuExample2 extends JFrame {
    
        public MenuExample2(String title) {
            super(title);
            JMenuBar mb = new JMenuBar();
            this.setJMenuBar(mb);
            JMenu fileMenu = new JMenu("File");
            mb.add(fileMenu);
            newItem = new JMenuItem("New...");
            openItem = new JMenuItem("Open...");
            closeItem = new JMenuItem("Close");
            fileMenu.add(newItem);
            fileMenu.add(openItem);
            fileMenu.add(closeItem);
            fileMenu.addSeparator();
            saveItem = new JMenuItem("Save");
            saveAsItem = new JMenuItem("Save As...");
            fileMenu.add(saveItem);
            fileMenu.add(saveAsItem);
            fileMenu.addSeparator();
            fileListMenu = new JMenu("Recent Files");
            fileMenu.add(fileListMenu);
            emptyListItem = new JMenuItem("Empty");
            emptyListItem.setEnabled(false);
            fileListMenu.add(emptyListItem);
            fileMenu.addSeparator();
            JMenuItem exitItem = new JMenuItem("Exit");
            fileMenu.add(exitItem);
            exitItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    closeWindow();
                }
            });
    
            this.getContentPane().add(new JScrollPane(textArea = new JTextArea(20, 40)));
            fileManager = new FileManager();
            // Processing for "New..." menu item
            newItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    String name = getFileName("New File", FileDialog.SAVE);
                    if (name != null) {
                        if (fileManager.isFileOpen()) {
                            // Close any open file
                            try {
                                fileManager.closeFile(textArea.getText());
                            } catch (Throwable e) {
                                // Ignore any exception
                            }
                        }
                        try {
                            fileManager.newFile(name);
                            textArea.setText("");
                            addRecentFile(name);
                        } catch (IOException e) {
                            // Do nothing - message already printed
                        }
                    }
                }
            });
            // Processing for "Open..." menu item
            openItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    String name = getFileName("Open File", FileDialog.LOAD);
                    if (name != null) {
                        try {
                            String text = fileManager.openFile(name);
                            textArea.setText(text);
                            addRecentFile(name);
                        } catch (IOException e) {
                                // Do nothing - message already printed
                        }
                    }
                }
            });
                // Processing for "Close..." menu item
            closeItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    try {
                        fileManager.closeFile(textArea.getText());
                        textArea.setText("");
                    } catch (IOException e) {
                        // Do nothing - message already printed
                    }
                }
            });
            // Processing for "Save..." menu item
            saveItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    try {
                        fileManager.saveFile(textArea.getText());
                    } catch (IOException e) {
                    // Do nothing - message already printed
                    }
                }
            });
            // Processing for "Save As..." menu item
            saveAsItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    if (fileManager.isFileOpen()) {
                        String name = getFileName("Save As File", FileDialog.SAVE);
                        if (name != null) {
                            try {
                                fileManager.saveAsFile(name, textArea.getText());
                            } catch (IOException e) {
                                // Do nothing - message already printed
                            }
                        }
                    }
                }
            });
            // Create the handler for the recent file list
            menuListener = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    JMenuItem mi = (JMenuItem)(evt.getSource());
                    String fileName = mi.getActionCommand();
                    try {
                        String text = fileManager.openFile(fileName);
                        textArea.setText(text);
                        addRecentFile(fileName);
                    } catch (IOException e) {
                        // Do nothing - message already printed
                    }
                }
            };
        }
    
        // Add a name to the recent file list
        public void addRecentFile(String fileName) {
            int offset;
            // Check whether this file is already in the file list
            if ((offset = recentFiles.indexOf(fileName)) == -1) {
                // Not present - add it at the beginning
                recentFiles.insertElementAt(fileName, 0);
                if (recentFiles.size() > RECENT_FILES) {
                    // List was full - remove the last (oldest) item
                    recentFiles.removeElementAt(RECENT_FILES);
                }
            } else {
                // Already present: move this item to the front of the list
                recentFiles.removeElementAt(offset);
                recentFiles.insertElementAt(fileName, 0);
            }
                // Rebuild the file menu
            buildRecentFileMenu();
        }
    
        // Build the recent file menu
        public void buildRecentFileMenu() {
            int size = recentFiles.size();
            fileListMenu.removeAll();
            for (int i = 0; i < size; i++) {
                String fileName = (String)(recentFiles.elementAt(i));
                JMenuItem mi = new JMenuItem(fileName);
                fileListMenu.add(mi);
                mi.addActionListener(menuListener);
            }
        }
    
        // Get a file name
        public String getFileName(String title, int mode) {
            FileDialog fd = new FileDialog(this, title, mode);
            fd.setFile("*.*");
            fd.setDirectory(directory);
            fd.setVisible(true);
            String dir = fd.getDirectory();
            String file = fd.getFile();
            if (dir == null || file == null) {
                return null;
            }
            directory = dir;
            String separator = System.getProperty("file.separator");
            if (dir.endsWith(separator)) {
                return dir + file;
            } else {
                return dir + separator + file;
            }
        }
    
        // Take any action needed to close the application
        public void closeWindow() {
            try {
                fileManager.closeFile(textArea.getText());
            } catch (IOException e) {
                System.out.println("Failed to write data on close.");
            }
            System.exit(0);
        }
    
        public static void main(String[] args) {
            JFrame f = new MenuExample2("Menu Example 2");
            f.pack();
            f.setVisible(true);
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    MenuExample2 frame = (MenuExample2)(evt.getSource());
                    frame.closeWindow();
                }
            });
        }
        JMenuItem newItem;
        JMenuItem openItem;
        JMenuItem closeItem;
        JMenuItem saveItem;
        JMenuItem saveAsItem;
        JMenuItem emptyListItem;
        JMenu fileListMenu;
        JTextArea textArea;
        FileManager fileManager;
        String directory = "";	 // Current directory
        ActionListener menuListener;
        // Recently-used file list
        static final int RECENT_FILES = 4;
        Vector recentFiles = new Vector(RECENT_FILES);
    }

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: confusing name repite

    It's not the way I would have written the Filemanager, but that's a different canWrite() method.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  11. #11
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    what you mean here tolls "but that's a different canWrite() method"
    (I should say to the defense of the author of JFC book that, that code is part
    of a large series of menu codes (12) and that each one improves in context etc.
    of course not knowing your criticism concerning that code....)
    Last edited by willemjav; 12-12-2013 at 01:11 PM.

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: confusing name repite

    You must understand methods by now, surely?
    This code:
    Java Code:
    canWriteFile = openFile.canWrite();
    is using a different method than this code:
    Java Code:
    canWriteFile = canWrite();
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    When there would be a class OpenFile and one creates an object openFile like this:
    OpenFile openFile = new OpenFile();
    The line:
    openFile.canWrite();
    would invoke the method canWrite() (returning a boolean) of that class, right!

    But since openFile is not a class but a method and variable of the type File AT THE SAME TIME....
    one might get a little lost here, right?

    So my question is what does openFile.canWrite(); means in this particular context?
    Last edited by willemjav; 12-12-2013 at 01:52 PM.

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: confusing name repite

    It is not a method and a variable at the same time.
    Java Code:
    openFile("some file");
    is calling the method.
    Java Code:
    openFile.canWrite();
    is calling the canWrite method on the attribute, which is of class File.
    The compiler understands this, and knows that that openFile cannot be the method, because that is syntactically incorrect.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  15. #15
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: confusing name repite

    Deja vu, I thought we were passed this already :s I guess not.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  16. #16
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    I know gb, but you should know, I study this stuff many, many hours each day and usually things go just fine,
    but sometimes things get blocked (so be my shrink)......

    Tolls, is there any obvious reason for doing that call: openFile.canWrite(); (instead of this.canWrite())
    concerning the context where it is in?

  17. #17
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    Or even worse gb2: why is the compiler not saying:
    error no such method "canWrite()" at the class "File" when trying to code openFile.canWrite()?
    (assuming that openFile is an object of the class File)

  18. #18
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    Shit, I just checked the api and it is there haaaaaaleeeeeeeeluuuuuuuujaaaaaaaa
    So that method was not created freely,
    but was overwritten, wow!
    Last edited by willemjav; 12-12-2013 at 02:28 PM.

  19. #19
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: confusing name repite

    I didn't realize that was ever in doubt. Glad that you got your mind sorted out, but I hope you realize that this thread proves that you work a bit too chaotically for your own good.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  20. #20
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: confusing name repite

    Yes now I see that the file class has a lot of those methods of the discussed FileManager class here!
    All these methods are adding to the functionality of the class.... I get a notion of what tolls is saying...
    gb2, I do not work chaotically, the opposite is true (I compile very carefully reductions of all I study,
    already more than 500 pages. and add all code samples to it!

    But like I said before, sometimes I get blocked because of the mountains of codes I am studying.
    So there will be more of this in the future...

    thanks, for your patience!

Similar Threads

  1. Confusing Error
    By CODinacup in forum New To Java
    Replies: 1
    Last Post: 10-02-2012, 05:44 AM
  2. A very confusing question
    By JohnPringle83 in forum New To Java
    Replies: 3
    Last Post: 05-08-2011, 08:29 AM
  3. confusing ques
    By rok0016 in forum New To Java
    Replies: 6
    Last Post: 07-15-2010, 07:07 PM
  4. Confusing with bitwise NOT operator
    By Willi in forum New To Java
    Replies: 4
    Last Post: 10-17-2009, 12:06 AM
  5. Confusing with Frameworks
    By hisouka in forum New To Java
    Replies: 0
    Last Post: 08-05-2008, 06:52 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •