Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replaced some getField and fixed some bugs #1631

Merged
merged 5 commits into from
Jul 29, 2016

Conversation

oscargus
Copy link
Contributor

Thanks to @Siedlerchr reminding me about the brilliance of Optional, I decided to try and convert some BibEntry.getField to BibEntry.getFieldOptional in a "proper" way. I managed in a few positions, but more importantly i reinstalled Find bugs as a consequence of this.

I found a few quite bad bugs, such as NPEs when clicking "Browse" in the journal management dialog with an empty text field. Also, there where some other example of introducing requireNonNull without really checking that all existing calling functions did call without a null hard coded...

@Siedlerchr as I know that you are a big fan of Path, Find bugs complains that some method there is quite likely to return null (I think getPath()), so stacking a number of method calls is claimed to be risky.

Still a few to be fixed (appending a database with explicit groups will most likely not work at the moment), but I leave that to the persons introducing them.

  • Manually tested changed features in running JabRef

@oscargus oscargus added bug Confirmed bugs or reports that are very likely to be bugs cleanup-ops status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers labels Jul 26, 2016
StringBuffer sbOrig = new StringBuffer(content);
StringBuffer sbLower = new StringBuffer(content.toLowerCase());
StringBuffer haystack = caseSensitive ? sbOrig : sbLower;
String needle = caseSensitive ? searchExpression : searchExpression.toLowerCase();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What the hell is that for a method?
needlehaystack

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The marvel of JabRef. 😄

@Siedlerchr
Copy link
Member

Regarding the fileDialogs and eventual nulls, please don't change that much, as I am rewriting them completely in #1336. I will only make merging harder ;)

@oscargus
Copy link
Contributor Author

I only changed where the extension List was set to null and where the un-null setting of a File was optional leading to an NPE. The "possible" nulls I leave. :-)

@oscargus
Copy link
Contributor Author

Added CHANGELOG entries for the NPE bugs I corrected. @JabRef/developers : I think we should try and merge those fixes before next release. ;-)

@oscargus oscargus added this to the v3.6 milestone Jul 28, 2016
if (o == null) {
return false;
}

boolean equalName = this.getName().equals(((CustomImporter) o).getName());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The equals methods looks a bit weird, it should follow a more clear pattern. A possible good solution would be this:

        @Override
        public boolean equals(Object other)
        {
            if (other == null) // Null-check
                return false;

            if (this == other) // reflexivity 
                return true;

            if (this.getClass() != other.getClass()) // Type safety 
                return false;

            final CustomImpoter importer = (CustomImporter) other;
            return Objects.equals() && ...
        }

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is correct. Implementations of equals should always follow a very narrow contract. @oscargus: If you are interested, this is excellently described in Effective Java 2nd Edition, Item 8: "Obey the general contract when overriding equals" (I won't link a pdf version here, but I am sure you can find one if you desire).

Most IDEs can auto-generate you a good implementation of equals these days.

@oscargus
Copy link
Contributor Author

I checked the 35 equals methods of JabRef and there is clearly not a single pattern in how they are implemented. I'm not sure if getClass is the universal solution here. Sure, it is faster than instanceof but the use is dependent on the class, see e.g. http://stackoverflow.com/questions/4989818/instanceof-vs-getclass

Might be good to get some consensus on this and add it to the code guidelines.

The other interesting question is if this should stop merging. Now I have updated it, but in this PR this was a very minor part and the alternative would have been to just not introduce the null check in the first place. The question is really if that would have been a better alternative? It is another thing if issues are introduced by incomplete code. To me it is not a problem, but I am thinking how new contributors react. There is a risk that they won't fix these minor issues if they are part of a bigger one or that they will stop contributing.

@lenhard
Copy link
Member

lenhard commented Jul 29, 2016

Regarding equals consensus is easy. Effective Java sets the standard here. Let me quote the rules for implementing equals (for a deeper explanation, please refer to the book):

  1. Use the == operator to check if the argument is a reference to this object. If so, return true.
  2. Use the instanceof operator to check if the argument has the correct type. f not, return false.
  3. Cast the argument to the correct type.
  4. For each “significant” field in the class, check if that field of the argument matches the corresponding field of this object. If all these tests succeed, return true otherwise, return false.
  5. When you are finished writing your equals method, ask yourself three questions: Is it symmetric? Is it transitive? Is it consistent?

Also, note:

  • Always override hashCode when you override equals (hashCode also has very strict rules)
  • Don’t try to be too clever
  • Don’t substitute another type for Object in the equals declaration

Regarding JabRef, most equals methods are probably broken in one way or the other. We should gradually replace these with correct implementations. From my point of view, incorrect equals methods should prohibit the merging of a PR. It is not so hard to implement a correct one (since most IDEs generate it), so it something that we can ask from people in my point of view. If you do it, it should be correct. As a side note, your implementation does not fully follow the rules, the first null check is not necessary as it is included in the third check (null instanceof SomeClass will always return false). This is just a performance issue, though, not a correctness one. However, you still need to provide a proper implementation of hashCode, otherwise the classes will fail to work when used in a HashMap. I'd suggest you let your IDE generate an implementation.

@oscargus
Copy link
Contributor Author

My point was rather going from a broken equals to a slightly less broken equals (which is what happened here) rather than introducing a broken equals. Was the alternative of not touching the equals at all better? Simpler for sure.

I agree with you and, apart from the this == oher check is more or less how I usually write mine (no explicit checking for null).

Eclipse seems not to be one of those IDEs though. Or I haven't found the switch to make it more clever than super(other)...

@lenhard
Copy link
Member

lenhard commented Jul 29, 2016

You would have gotten away without touching equals ;-) My point is: If you touch it, you should go all the way.

Eclipse generates you these methods via the menu: Source-> "Generate hashCode() and equals()". Your cursor needs to be in the class in which you want to generate the methods. In the following dialog, you can select the significant attributes of the class.

@oscargus
Copy link
Contributor Author

Yes, that's my point. My question is if that is better? ;-)

Ahh, OK! Thanks! The generation based on warnings seems to be different.

@oscargus
Copy link
Contributor Author

I added your bullets in the Wiki.

@lenhard
Copy link
Member

lenhard commented Jul 29, 2016

Great! So this PR is now good to go, right? (at least from my point of view)

@oscargus oscargus mentioned this pull request Jul 29, 2016
@Siedlerchr
Copy link
Member

Be warned about the Eclipse generated equals methods, it is not always ideal/correct.
using instanceOf makes sense if you want subtypes to be equal. But that is a philsophocial questions...;)
And for HashCode there is the nice Object.hash() method.

@oscargus
Copy link
Contributor Author

I merge this now. Do not think it can be much better. ;-)

@oscargus oscargus merged commit 5416f4f into JabRef:master Jul 29, 2016
@oscargus oscargus deleted the getfieldoptional branch July 29, 2016 10:58
Siedlerchr added a commit to Siedlerchr/jabref that referenced this pull request Jul 30, 2016
* master:
  Unified some equals (JabRef#1640)
  Export OO/LO citations to new database (JabRef#1630)
  Fixed JabRef#1639 (JabRef#1641)
  Replaced some getField and fixed some bugs (JabRef#1631)
  Keep @comment text in a bib file (JabRef#1638)

# Conflicts:
#	src/main/java/net/sf/jabref/importer/AppendDatabaseAction.java
oscargus added a commit to oscargus/jabref that referenced this pull request Jul 30, 2016
ayanai1 pushed a commit to ayanai1/jabref that referenced this pull request Aug 1, 2016
Move event (JabRef#1601)

* Move event package to model

Update dependencies: postgres 9.4.1208 -> 9.4.1209 and wiremock from 2.1.6 to 2.1.7

Added ISBN integrity checker (JabRef#1586)

 Added ISBN integrity checker

* Extracted ISBN class

Reenable errorprone (see http://errorprone.info/)

Extend the OpenConsoleFeature (JabRef#1582)

* Extend the OpenConsoleFeature by selection of custom terminal emulator.

- Add radio selection to the AdvancedTab
- Add new JabRefPreferences
- Add file check and execution commands
- Add localization keys

* Fix localization key.

* Move console selection to ExternalTab.java

* Change localization entry.

* Add command executor.

* Fix placeholder replacement.

* Fix codacy.

* Update localization key.

* Remove "Specify terminal emulator" option. Add GUI outputs.

* Set default command for Windows. Fix localization entries.

* Remove empty lines in language files.

* Use lambda expressions insead of ActionListeners

* Refactoring.

* Update CHANGELOG.md.

* Small refactorings.

Move preferences (JabRef#1604)

* Move preferences-related classes into separate package

* Rename JabRefPreferencesFilterDialog -> PreferencesFilterDialog and move it to gui

* Fix checkstyle warning

Set user agent to fix 403 status error

Replace getField with getFieldOptional in all of the tests and in som… (JabRef#1591)

* Replace getField with getFieldOptional in all of the tests and in some more code

* Some more conversions

Added filter to not show selected integrity checks (JabRef#1588)

* Added filter to not show selected integrity checks

* Removed unused variable

Some Globals.prefs injection in logic and model (JabRef#1593)

* Some Globals.prefs injection in logic and model

* Some more conversions and some fixes

* More injections

* Even more injections

* Yes, even more injections

* Indeed, even more injections

* Probably the last injections for now

* Removed unrequired dependency and fixed issue

* Dropped support for selecting sub/super to equations

* Added preference classes for LatexFieldFormatter and FieldContentParser

* Removed some left over code

* Added JournalAbbreviationPreferences

* Encapsulated LatexFieldFormatterPreferences in SavePreferences

* Changed getShortDescription to accept boolean argument

* Removed Globals.prefs from tests and removed unused imports

* Unused import

* Unused import

Rewrite MedlineImporter with JAXB and add nbib fields (JabRef#1479)

Add test in BibEntryWriterTest for type change

When clicking on a tab, the first field now has the focus (JabRef#988)

* the first Field does now have focus when clicking on a tab in the entry editor
* Make first field focused when selecting a tab in entry editor

The field list gets the focus as soon as it is focused (JabRef#1541)

Test CustomImporter (JabRef#1501)

* Test CustomImporter

Fixes imports

Added model.entry.FieldName that contains field name constants (JabRef#1602)

* Added model.entry.FieldName that contains field name constants

* More constants

* Renamed and added more constants

* Some more fields and cleanups

* Removed MedlineHandler left from merge conflicts

More fields added to FieldName (JabRef#1614)

* More fields added to FieldName

* Some Medline fixes

[WIP] Create new fetcher infrastructure (JabRef#1594)

* Introduce new Fetcher interfaces

* Refactor arXiv fulltext fetcher

* Add query based arXiv fetcher

* Reformat code

* Add a few tests for the arxiv parser

* Make new arXiv fetcher available

* Fix small problems related to files

* Fix tests

* Rename interface methods

* Add changelog entry

* Mark old EntryFetcher interface as deprecated

* Move fetcher to importer \ fetcher

* Move HelpFile from gui.help to logic.help

* Rename fetchers

* Rename FulltextFinder

* Optimize imports

* Fix failing test

* Ignore failing test

Added LayoutFormatterPreferences (and related files) (JabRef#1608)

* Added LayoutFormatterPreferences (and related files)

* Rebased

* Included JournalAbbreviationLoader in LayoutPreferences

Added more fields and fixed some issues (JabRef#1617)

Resolves JabRef#1613 Use Jabref default icon for uninstaller for now (JabRef#1616)

Always use https for help files (JabRef#1615)

Implemented JabRef#1345 - cleanup ISSN (JabRef#1590)

* Implemented JabRef#1345 - cleanup ISSN

* Fixed comments

* Extracted ISSN class

* Added tests for ISSN and ISBN

Added DateFormatter to LayoutEntry so that it actually works... (JabRef#1619)

Converted a few getField to getFieldOptional (JabRef#1625)

* Converted a few getField to getFieldOptional

Fixed JabRef#636 by using DOICheck and DOIStrip in export filters (JabRef#1624)

Improved LaTeX to Unicode/HTML formatters to output more sensible values for unknown commands (JabRef#1622)

Updated preview entries (JabRef#1606)

* Updated preview entries, which return new entry

Moved, removed, and used String constants (JabRef#1618)

* Moved, removed, and used String constants

* Some more fixes

* Moved NEWLINE, made FILE_SEPARATOR public and used it

* Moved NEWLINE and FILE_SEPARATOR to OS

* Moved ENCODING_PREFIX and SIGNATURE

* Corrected Globals in a few comments...

* Apparently the localization tests find commented out text...

More field names and a method (JabRef#1627)

* Introduced FieldName in ArXiV

* Some more field names

* More field names

Cleanup FindFile and asssociated tests (JabRef#1596)

* Cleanup FindFile and rework it using Streams and nio methods-
* Unignore test for trying on CI
* Use explicit List and Set in findFiles and caller methods
* Use Lazy Stream to find files

changes should be tested manually

Some enhancements and cleanups related to dates (JabRef#1575)

* Some enhancements and cleanups related to dates

* Fixed some time zone issues

* Replaced SimpleDateFormat in ZipFileChooser and replaced arrays with Lists

* Changed EasyDateFormat constructors

* Fixed stupid mistake

* Added CHANGELOG entry

* Maybe tests are passing now?

* Some server side print debugging...

* As it should be

* Tryng LocalDateTime

* No time zone

* Added test for Cookie

* Fixed imports...

* Added a third possible date format as it turns out that the server changed while developing this PR

Builds are now stored via build-upload.jabref.org

Consistent file name casing (and other localization improvements) (JabRef#1629)

* AUX files

* ZIP files

* BIB files

* JAR files

* didn't

* Couldn't what's

* Consistent casing

* AUX apparently is commonly used in French words...

* Fixed the flawed quick-and-dirty find-and-replace failures

define xjc input/ouput dir (subsequent builds will be faster) (JabRef#1628)

Execute task only when input/output dir changed.

Fixed a minor issue and refactored MergeEntries (JabRef#1634)

* Fixed a minor issue and refactored MergeEntries

* Fixed import

* Added CHANGELOG entry

Added LabelPatternPreferences (JabRef#1607)

* Added LabelPatternPreferences

* Removed static initializer

More tests (JabRef#1635)

* Added more tests for Cookie

* Enabled some layout tests and added test for StringUtil.intValueOfWithNull

* Updated a test

* Split tests

Updated Errorprone to 2.0.11 (JabRef#1636)

* Updated Errorprone to 2.0.11

* Corrected test

Keep @comment text in a bib file (JabRef#1638)

* Kep @comment text in a bib file

* Add test for @comment that contains regular entries

Replaced some getField and fixed some bugs (JabRef#1631)

* Replaced some getField and fixed some bugs

* Fixed a few things

* Added CHANGELOG entries

* Improved equals implementation

* Text book equals and hashCode

Fixed JabRef#1639 (JabRef#1641)

* Fixed JabRef#1639

* Removed old code

Export OO/LO citations to new database (JabRef#1630)

* Export OO/LO citations to new database

* Fixed problem with duplicates

* Added some comments

* Fixed spelling in comment

* Removed general Exception

Unified some equals (JabRef#1640)

* Unified some equals

* Imported correct Objects...

Fixed one more NPE which should have been fixed in JabRef#1631 (JabRef#1649)

Finished method to hide visible fields and show hidden fields

- Hide method done
- Show method done
- ToDo repaint hidden field
- ToDo test class

finished field repaint

remove sysouts
Siedlerchr added a commit to Siedlerchr/jabref that referenced this pull request Aug 1, 2016
* master:
  French localization: Menu (JabRef#1657)
  Fixed one more NPE which should have been fixed in JabRef#1631 (JabRef#1649)
@oscargus oscargus mentioned this pull request Aug 11, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Confirmed bugs or reports that are very likely to be bugs cleanup-ops status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants