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

Add null pointer check to avoid null pointer exception. #117

Merged
merged 1 commit into from
Jun 11, 2024

Conversation

Xiqinger
Copy link
Contributor

The code for the 'StateInstance' class is as follows. In order to ensure that 'regimeHM' is not null and non-empty when calling 'transitionTo' and 'initRefime', the 'addRegime' method must be called beforehand.

public class StateInstance ... {
    	public void transitionTo(String rnm) throws RuntimeError {
		activeRegime = regimeHM.get(rnm);
		activeRegime.enter();
	}
...
	public void initRegime() throws RuntimeError {
		if (activeRegime == null) {
			activeRegime = regimeHM.get(regimeHM.keySet().iterator().next());
			// TODO just picks random regime
		}
		activeRegime.enter();
	}
...
	public void addRegime(RegimeStateInstance rsi) {
		hasRegimes = true;
		if (regimeHM == null) {
			regimeHM = new HashMap<String, RegimeStateInstance>();
		}
		regimeHM.put(rsi.getID(), rsi);
		// E.info("state instance added regime " + rsi.getID());
		if (rsi.isInitial()) {
			activeRegime = rsi;
		}

	}
}

However, the instance construction of StateInstance is located in the 'ownNewInstance' method of the StateType class, and it is not guaranteed that 'addRegime' will always be called. This can potentially lead to NullPointerExceptions if 'regimeHM' is not properly initialized.

public class StateType implements RuntimeType, ILEMSStateType {
    private StateInstance ownNewInstance() throws ContentError, ConnectionError, RuntimeError {
        ...
		if (hasRegimes) {
			for (String srn : regimeHM.keySet()) {
				ComponentRegime cr = regimeHM.get(srn);
				RegimeStateInstance rsi = cr.newInstance(uin);
				uin.addRegime(rsi); 
			}
		}

While NullPointerException is a type of RuntimeException, distinguishing between different types of exceptions can indeed help developers better understand the cause of the exception.

@pgleeson
Copy link
Member

Thanks for this @Xiqinger. I'm travelling now but will have a look at it in the next few days.

@pgleeson pgleeson changed the base branch from master to development May 17, 2024 10:38
@pgleeson pgleeson merged commit acebdca into LEMS:development Jun 11, 2024
28 of 30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants